CharField
(documentation)
from Django's forms
module enables safe handling of
alphanumeric data via an HTTP POST request that includes data from an
HTML form generated by a
web application.
dccnsys is a conference registration system built with Django. The code is open source under the MIT license.
dccnsys / wwwdccn / chair / forms.py
# forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from conferences.models import Conference
from gears.widgets import CustomCheckboxSelectMultiple, CustomFileInput
from review.models import Reviewer, Review
from submissions.models import Submission
from users.models import Profile
User = get_user_model()
COMPLETION_STATUS = [
('EMPTY', 'Empty submissions'),
('INCOMPLETE', 'Incomplete submissions'),
('COMPLETE', 'Complete submissions'),
]
class FilterSubmissionsForm(forms.ModelForm):
class Meta:
model = Conference
fields = []
term = forms.CharField(required=False)
completion = forms.MultipleChoiceField(
widget=CustomCheckboxSelectMultiple, required=False,
choices=COMPLETION_STATUS,
)
types = forms.MultipleChoiceField(
widget=CustomCheckboxSelectMultiple, required=False,
)
topics = forms.MultipleChoiceField(
widget=CustomCheckboxSelectMultiple, required=False,
)
status = forms.MultipleChoiceField(
widget=CustomCheckboxSelectMultiple, required=False,
choices=Submission.STATUS_CHOICE
)
countries = forms.MultipleChoiceField(
widget=CustomCheckboxSelectMultiple, required=False,
)
affiliations = forms.MultipleChoiceField(
widget=CustomCheckboxSelectMultiple, required=False,
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
assert isinstance(self.instance, Conference)
self.fields['types'].choices = [
(st.pk, st) for st in self.instance.submissiontype_set.all()
]
self.fields['topics'].choices = [
(topic.pk, topic) for topic in self.instance.topic_set.all()
]
# Getting profiles of all participants:
profiles = Profile.objects.filter(
user__authorship__submission__conference__pk=self.instance.pk
).distinct()
# Extracting all the different countries:
countries = list(set(p.country for p in profiles))
countries.sort(key=lambda cnt: cnt.name)
self.fields['countries'].choices = [
(cnt.code, cnt.name) for cnt in countries
]
# Extracting all the different affiliations:
affs = [item['affiliation'] for item in profiles.values('affiliation')]
affs.sort()
self.fields['affiliations'].choices = [(item, item) for item in affs]
def apply(self, submissions):
term = self.cleaned_data['term']
completion = self.cleaned_data['completion']
types = [int(t) for t in self.cleaned_data['types']]
topics = [int(topic) for topic in self.cleaned_data['topics']]
status = self.cleaned_data['status']
countries = self.cleaned_data['countries']
affiliations = self.cleaned_data['affiliations']
auth_prs = {
sub: Profile.objects.filter(user__authorship__submission=sub)
for sub in submissions
}
if term:
words = term.lower().split()
submissions = [
sub for sub in submissions
if all(word in sub.title.lower() or
any(word in pr.get_full_name().lower()
for pr in auth_prs[sub]) or
any(word in pr.get_full_name_rus().lower()
for pr in auth_prs[sub])
for word in words)
]
if completion:
_show_incomplete = 'INCOMPLETE' in completion
_show_complete = 'COMPLETE' in completion
_show_empty = 'EMPTY' in completion
_sub_warnings = {sub: sub.warnings() for sub in submissions}
submissions = [
sub for sub in submissions
if (_sub_warnings[sub] and _show_incomplete or
not _sub_warnings[sub] and _show_complete or
not sub.title and _show_empty)
]
if topics:
_sub_topics = {
sub: set(x[0] for x in sub.topics.values_list('pk'))
for sub in submissions
}
submissions = [
sub for sub in submissions
if any(topic in _sub_topics[sub] for topic in topics)
]
if types:
submissions = [sub for sub in submissions
if sub.stype and sub.stype.pk in types]
if status:
submissions = [sub for sub in submissions if sub.status in status]
if countries:
submissions = [
sub for sub in submissions
if any(pr.country.code in countries for pr in auth_prs[sub])
]
if affiliations:
submissions = [
sub for sub in submissions
if any(pr.affiliation in affiliations for pr in auth_prs[sub])
]
return submissions
ATTENDING_STATUS = (
('YES', 'Attending'),
('NO', 'Not attending'),
)
class FilterUsersForm(forms.ModelForm):
class Meta:
model = Conference
fields = []
term = forms.CharField(required=False)
attending_status = forms.MultipleChoiceField(
widget=CustomCheckboxSelectMultiple, required=False,
choices=ATTENDING_STATUS,
)
## ... source file continues with no further CharField examples ...
django-allauth (project website) is a Django library for easily adding local and social authentication flows to Django projects. It is open source under the MIT License.
django-allauth / allauth / account / forms.py
from __future__ import absolute_import
import warnings
from importlib import import_module
from django import forms
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.sites.shortcuts import get_current_site
from django.core import exceptions, validators
from django.urls import reverse
from django.utils.translation import pgettext
from allauth.compat import ugettext, ugettext_lazy as _
from ..utils import (
build_absolute_uri,
get_username_max_length,
set_form_field_order,
)
from . import app_settings
from .adapter import get_adapter
from .app_settings import AuthenticationMethod
from .models import EmailAddress
from .utils import (
filter_users_by_email,
get_user_model,
perform_login,
setup_user_email,
sync_user_email_addresses,
url_str_to_user_pk,
user_email,
user_pk_to_url_str,
user_username,
)
class EmailAwarePasswordResetTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
ret = super(
EmailAwarePasswordResetTokenGenerator, self)._make_hash_value(
user, timestamp)
sync_user_email_addresses(user)
emails = set([user.email] if user.email else [])
emails.update(
EmailAddress.objects
.filter(user=user)
.values_list('email', flat=True))
ret += '|'.join(sorted(emails))
return ret
default_token_generator = EmailAwarePasswordResetTokenGenerator()
class PasswordVerificationMixin(object):
def clean(self):
cleaned_data = super(PasswordVerificationMixin, self).clean()
password1 = cleaned_data.get('password1')
password2 = cleaned_data.get('password2')
if (password1 and password2) and password1 != password2:
self.add_error(
'password2', _("You must type the same password each time.")
)
return cleaned_data
class PasswordField(forms.CharField):
def __init__(self, *args, **kwargs):
render_value = kwargs.pop('render_value',
app_settings.PASSWORD_INPUT_RENDER_VALUE)
kwargs['widget'] = forms.PasswordInput(render_value=render_value,
attrs={'placeholder':
kwargs.get("label")})
super(PasswordField, self).__init__(*args, **kwargs)
class SetPasswordField(PasswordField):
def __init__(self, *args, **kwargs):
super(SetPasswordField, self).__init__(*args, **kwargs)
self.user = None
def clean(self, value):
value = super(SetPasswordField, self).clean(value)
value = get_adapter().clean_password(value, user=self.user)
return value
class LoginForm(forms.Form):
password = PasswordField(label=_("Password"))
remember = forms.BooleanField(label=_("Remember Me"),
required=False)
user = None
error_messages = {
'account_inactive':
_("This account is currently inactive."),
'email_password_mismatch':
_("The e-mail address and/or password you specified are not correct."),
'username_password_mismatch':
_("The username and/or password you specified are not correct."),
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(LoginForm, self).__init__(*args, **kwargs)
if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL:
login_widget = forms.TextInput(attrs={'type': 'email',
'placeholder':
_('E-mail address'),
'autofocus': 'autofocus'})
login_field = forms.EmailField(label=_("E-mail"),
widget=login_widget)
elif app_settings.AUTHENTICATION_METHOD \
== AuthenticationMethod.USERNAME:
login_widget = forms.TextInput(attrs={'placeholder':
_('Username'),
'autofocus': 'autofocus'})
login_field = forms.CharField(
label=_("Username"),
widget=login_widget,
max_length=get_username_max_length())
else:
assert app_settings.AUTHENTICATION_METHOD \
== AuthenticationMethod.USERNAME_EMAIL
login_widget = forms.TextInput(attrs={'placeholder':
_('Username or e-mail'),
'autofocus': 'autofocus'})
login_field = forms.CharField(label=pgettext("field label",
"Login"),
widget=login_widget)
self.fields["login"] = login_field
set_form_field_order(self, ["login", "password", "remember"])
if app_settings.SESSION_REMEMBER is not None:
del self.fields['remember']
## ... source file continues with a few more similar CharField examples ...
django-cms (project website) is a Python-based content management system (CMS) library for use with Django web apps that is open sourced under the BSD 3-Clause "New" license.
django-cms / cms / forms / wizards.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils.text import slugify
from django.utils.translation import (
ugettext,
ugettext_lazy as _,
)
from cms.admin.forms import AddPageForm
from cms.plugin_pool import plugin_pool
from cms.utils import get_current_site, permissions
from cms.utils.page import get_available_slug
from cms.utils.page_permissions import (
user_can_add_page,
user_can_add_subpage,
)
from cms.utils.conf import get_cms_setting
from cms.utils.urlutils import static_with_version
try:
# djangocms_text_ckeditor is not guaranteed to be available
from djangocms_text_ckeditor.widgets import TextEditorWidget
text_widget = TextEditorWidget
except ImportError:
text_widget = forms.Textarea
class SlugWidget(forms.widgets.TextInput):
"""
Special widget for the slug field that requires Title field to be there.
Adds the js for the slugifying.
"""
class Media:
js = (
'admin/js/urlify.js',
static_with_version('cms/js/dist/bundle.forms.slugwidget.min.js'),
)
class CreateCMSPageForm(AddPageForm):
page = None
sub_page_form = False
# Field overrides
menu_title = None
page_title = None
meta_description = None
content = forms.CharField(
label=_(u'Content'), widget=text_widget, required=False,
help_text=_(u"Optional. If supplied, will be automatically added "
u"within a new text plugin.")
)
class Media:
js = (
# This simply adds some JS for
# hiding/showing the content field based on the selection of this select.
'cms/js/widgets/wizard.pagetypeselect.js',
)
def __init__(self, *args, **kwargs):
self._site = get_current_site()
self._user = self.user
self._language = self.language_code
super(CreateCMSPageForm, self).__init__(*args, **kwargs)
self.fields['title'].help_text = _(u"Provide a title for the new page.")
self.fields['slug'].required = False
self.fields['slug'].widget = SlugWidget()
self.fields['slug'].help_text = _(u"Leave empty for automatic slug, or override as required.")
@staticmethod
def get_placeholder(page, slot=None):
"""
Returns the named placeholder or, if no «slot» provided, the first
editable, non-static placeholder or None.
"""
placeholders = page.get_placeholders()
if slot:
placeholders = placeholders.filter(slot=slot)
for ph in placeholders:
if not ph.is_static and ph.is_editable:
return ph
return None
def clean(self):
"""
Validates that either the slug is provided, or that slugification from
`title` produces a valid slug.
:return:
"""
data = self.cleaned_data
if self._errors:
return data
slug = data.get('slug') or slugify(data['title'])
parent_node = data.get('parent_node')
if parent_node:
base = parent_node.item.get_path(self._language)
path = u'%s/%s' % (base, slug) if base else slug
else:
base = ''
path = slug
data['slug'] = get_available_slug(self._site, path, self._language, suffix=None)
data['path'] = '%s/%s' % (base, data['slug']) if base else data['slug']
if not data['slug']:
raise forms.ValidationError("Please provide a valid slug.")
return data
def clean_parent_node(self):
# Check to see if this user has permissions to make this page. We've
# already checked this when producing a list of wizard entries, but this
# is to prevent people from possible form-hacking.
if self.page and self.sub_page_form:
# User is adding a page which will be a direct
# child of the current page.
parent_page = self.page
elif self.page and self.page.parent_page:
# User is adding a page which will be a right
# sibling to the current page.
parent_page = self.page.parent_page
else:
parent_page = None
if parent_page:
has_perm = user_can_add_subpage(self.user, target=parent_page)
else:
has_perm = user_can_add_page(self.user)
if not has_perm:
message = ugettext('You don\'t have the permissions required to add a page.')
raise ValidationError(message)
return parent_page.node if parent_page else None
def clean_slug(self):
# Don't let the PageAddForm validate this
# on the wizard it is not a required field
return self.cleaned_data['slug']
def get_template(self):
return get_cms_setting('PAGE_WIZARD_DEFAULT_TEMPLATE')
@transaction.atomic
def save(self, **kwargs):
from cms.api import add_plugin
new_page = super(CreateCMSPageForm, self).save(**kwargs)
if self.cleaned_data.get("page_type"):
return new_page
parent_node = self.cleaned_data.get('parent_node')
if parent_node and new_page.parent_page.is_page_type:
# the new page was created under a page-type page
# set the new page as a page-type too
new_page.update(
draft_only=True,
is_page_type=True,
in_navigation=False,
)
# If the user provided content, then use that instead.
content = self.cleaned_data.get('content')
plugin_type = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
plugin_body = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')
slot = get_cms_setting('PAGE_WIZARD_CONTENT_PLACEHOLDER')
if plugin_type in plugin_pool.plugins and plugin_body:
if content and permissions.has_plugin_permission(
self.user, plugin_type, "add"):
new_page.rescan_placeholders()
placeholder = self.get_placeholder(new_page, slot=slot)
if placeholder:
opts = {
'placeholder': placeholder,
'plugin_type': plugin_type,
'language': self.language_code,
plugin_body: content,
}
add_plugin(**opts)
return new_page
class CreateCMSSubPageForm(CreateCMSPageForm):
sub_page_form = True
django-filer (project documentation) is a file management library for uploading and organizing files and images in Django's admin interface. The project's code is available under the BSD 3-Clause "New" or "Revised" open source license.
django-filer / filer / admin / forms.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from django import forms
from django.conf import settings
from django.contrib.admin import widgets
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext as _
from ..models import ThumbnailOption
from ..utils.files import get_valid_filename
class AsPWithHelpMixin(object):
def as_p_with_help(self):
"Returns this form rendered as HTML <p>s with help text formated for admin."
return self._html_output(
normal_row='<p%(html_class_attr)s>%(label)s %(field)s</p>%(help_text)s',
error_row='%s',
row_ender='</p>',
help_text_html='<p class="help">%s</p>',
errors_on_separate_row=True)
class CopyFilesAndFoldersForm(forms.Form, AsPWithHelpMixin):
suffix = forms.CharField(required=False,
help_text=_("Suffix which will be appended to filenames of copied files."))
# TODO: We have to find a way to overwrite files with different storage backends first.
# overwrite_files = forms.BooleanField(required=False, help_text=_("Overwrite a file if there already exists a file with the same filename?"))
def clean_suffix(self):
valid = get_valid_filename(self.cleaned_data['suffix'])
if valid != self.cleaned_data['suffix']:
raise forms.ValidationError(_('Suffix should be a valid, simple and lowercase filename part, like "%(valid)s".') % {'valid': valid})
return self.cleaned_data['suffix']
class RenameFilesForm(forms.Form, AsPWithHelpMixin):
rename_format = forms.CharField(required=True)
def clean_rename_format(self):
try:
self.cleaned_data['rename_format'] % {
'original_filename': 'filename',
'original_basename': 'basename',
'original_extension': 'ext',
'current_filename': 'filename',
'current_basename': 'basename',
'current_extension': 'ext',
'current_folder': 'folder',
'counter': 42,
'global_counter': 42,
}
except KeyError as e:
raise forms.ValidationError(_('Unknown rename format value key "%(key)s".') % {'key': e.args[0]})
except Exception as e:
raise forms.ValidationError(_('Invalid rename format: %(error)s.') % {'error': e})
return self.cleaned_data['rename_format']
## ... source file continues with no further CharField examples ...
django-jet (project documentation, PyPI project page and more information) is a fancy Django Admin panel replacement.
The django-jet project is open source under the GNU Affero General Public License v3.0.
django-jet / jet / dashboard / forms.py
import json
from django import forms
from django.core.exceptions import ValidationError
from jet.dashboard.models import UserDashboardModule
from jet.dashboard.utils import get_current_dashboard
from jet.utils import user_is_authenticated
class UpdateDashboardModulesForm(forms.Form):
app_label = forms.CharField(required=False)
modules = forms.CharField()
modules_objects = []
def __init__(self, request, *args, **kwargs):
self.request = request
super(UpdateDashboardModulesForm, self).__init__(*args, **kwargs)
def clean(self):
data = super(UpdateDashboardModulesForm, self).clean()
if not user_is_authenticated(self.request.user) or not self.request.user.is_staff:
raise ValidationError('error')
try:
modules = json.loads(data['modules'])
for module in modules:
db_module = UserDashboardModule.objects.get(
user=self.request.user.pk,
app_label=data['app_label'] if data['app_label'] else None,
pk=module['id']
)
column = module['column']
order = module['order']
if db_module.column != column or db_module.order != order:
db_module.column = column
db_module.order = order
self.modules_objects.append(db_module)
except Exception:
raise ValidationError('error')
return data
def save(self):
for module in self.modules_objects:
module.save()
class AddUserDashboardModuleForm(forms.ModelForm):
type = forms.CharField()
module = forms.IntegerField()
module_cls = None
def __init__(self, request, *args, **kwargs):
self.request = request
super(AddUserDashboardModuleForm, self).__init__(*args, **kwargs)
class Meta:
model = UserDashboardModule
fields = ['app_label']
def clean_app_label(self):
data = self.cleaned_data['app_label']
return data if data != '' else None
def clean(self):
data = super(AddUserDashboardModuleForm, self).clean()
if not user_is_authenticated(self.request.user) or not self.request.user.is_staff:
raise ValidationError('error')
if 'app_label' in data:
index_dashboard_cls = get_current_dashboard('app_index' if data['app_label'] else 'index')
index_dashboard = index_dashboard_cls({'request': self.request}, app_label=data['app_label'])
if 'type' in data:
if data['type'] == 'children':
module = index_dashboard.children[data['module']]
elif data['type'] == 'available_children':
module = index_dashboard.available_children[data['module']]()
else:
raise ValidationError('error')
self.module_cls = module
return data
def save(self, commit=True):
self.instance.title = self.module_cls.title
self.instance.module = self.module_cls.fullname()
self.instance.user = self.request.user.pk
self.instance.column = 0
self.instance.order = -1
self.instance.settings = self.module_cls.dump_settings()
self.instance.children = self.module_cls.dump_children()
return super(AddUserDashboardModuleForm, self).save(commit)
class UpdateDashboardModuleCollapseForm(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
self.request = request
super(UpdateDashboardModuleCollapseForm, self).__init__(*args, **kwargs)
class Meta:
model = UserDashboardModule
fields = ['collapsed']
def clean(self):
data = super(UpdateDashboardModuleCollapseForm, self).clean()
if not user_is_authenticated(self.request.user) or not self.request.user.is_staff:
raise ValidationError('error')
if self.instance.user != self.request.user.pk:
raise ValidationError('error')
return data
class RemoveDashboardModuleForm(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
self.request = request
super(RemoveDashboardModuleForm, self).__init__(*args, **kwargs)
class Meta:
model = UserDashboardModule
fields = []
def clean(self):
cleaned_data = super(RemoveDashboardModuleForm, self).clean()
if not user_is_authenticated(self.request.user) or self.instance.user != self.request.user.pk:
raise ValidationError('error')
return cleaned_data
def save(self, commit=True):
if commit:
self.instance.delete()
class ResetDashboardForm(forms.Form):
app_label = forms.CharField(required=False)
def __init__(self, request, *args, **kwargs):
self.request = request
super(ResetDashboardForm, self).__init__(*args, **kwargs)
class Meta:
model = UserDashboardModule
fields = []
def clean(self):
data = super(ResetDashboardForm, self).clean()
data['app_label'] = data['app_label'] if data['app_label'] else None
if not user_is_authenticated(self.request.user) or not self.request.user.is_staff:
raise ValidationError('error')
return data
def save(self, commit=True):
if commit:
UserDashboardModule.objects.filter(
user=self.request.user.pk,
app_label=self.cleaned_data['app_label']
).delete()
django-mongonaut (project documentation and PyPI package information) provides an introspective interface for working with MongoDB via mongoengine. The project has its own new code to map MongoDB to the Django Admin interface.
django-mongonaut's highlighted features include automatic introspection of mongoengine documents, the ability to constrain who sees what and what they can do, and full control for adding, editing and deleting documents.
The django-mongonaut project is open sourced under the MIT License and it is maintained by the developer community group Jazzband.
django-mongonaut / mongonaut / forms / widgets.py
# -*- coding: utf-8 -*-
""" Widgets for mongonaut forms"""
from django import forms
from mongoengine.base import ObjectIdField
from mongoengine.fields import BooleanField
from mongoengine.fields import DateTimeField
from mongoengine.fields import EmbeddedDocumentField
from mongoengine.fields import ListField
from mongoengine.fields import ReferenceField
from mongoengine.fields import FloatField
from mongoengine.fields import EmailField
from mongoengine.fields import DecimalField
from mongoengine.fields import URLField
from mongoengine.fields import IntField
from mongoengine.fields import StringField
from mongoengine.fields import GeoPointField
def get_widget(model_field, disabled=False):
"""Choose which widget to display for a field."""
attrs = get_attrs(model_field, disabled)
if hasattr(model_field, "max_length") and not model_field.max_length:
return forms.Textarea(attrs=attrs)
elif isinstance(model_field, DateTimeField):
return forms.DateTimeInput(attrs=attrs)
elif isinstance(model_field, BooleanField):
return forms.CheckboxInput(attrs=attrs)
elif isinstance(model_field, ReferenceField) or model_field.choices:
return forms.Select(attrs=attrs)
elif (isinstance(model_field, ListField) or
isinstance(model_field, EmbeddedDocumentField) or
isinstance(model_field, GeoPointField)):
return None
else:
return forms.TextInput(attrs=attrs)
def get_attrs(model_field, disabled=False):
"""Set attributes on the display widget."""
attrs = {}
attrs['class'] = 'span6 xlarge'
if disabled or isinstance(model_field, ObjectIdField):
attrs['class'] += ' disabled'
attrs['readonly'] = 'readonly'
return attrs
def get_form_field_class(model_field):
"""Gets the default form field for a mongoenigne field."""
FIELD_MAPPING = {
IntField: forms.IntegerField,
StringField: forms.CharField,
FloatField: forms.FloatField,
BooleanField: forms.BooleanField,
DateTimeField: forms.DateTimeField,
DecimalField: forms.DecimalField,
URLField: forms.URLField,
EmailField: forms.EmailField
}
return FIELD_MAPPING.get(model_field.__class__, forms.CharField)