django.forms CharField Python Code Examples

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.

Example 1 from dccnsys

dccnsys is a conference registration system built with Django. The code is open source under the MIT license.

dccnsys / wwwdccn / chair /

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()

    ('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,

    types = forms.MultipleChoiceField(
        widget=CustomCheckboxSelectMultiple, required=False,

    topics = forms.MultipleChoiceField(
        widget=CustomCheckboxSelectMultiple, required=False,

    status = forms.MultipleChoiceField(
        widget=CustomCheckboxSelectMultiple, required=False,

    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) for st in self.instance.submissiontype_set.all()
        self.fields['topics'].choices = [
            (, topic) for topic in self.instance.topic_set.all()

        # Getting profiles of all participants:
        profiles = Profile.objects.filter(

        # Extracting all the different countries:
        countries = list(set( for p in profiles))
        countries.sort(key=lambda cnt:
        self.fields['countries'].choices = [
            (cnt.code, for cnt in countries

        # Extracting all the different affiliations:
        affs = [item['affiliation'] for item in profiles.values('affiliation')]
        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 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( 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

    ('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,

## ... source file continues with no further CharField examples ...

Example 2 from django-allauth

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 /

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 (
from . import app_settings
from .adapter import get_adapter
from .app_settings import AuthenticationMethod
from .models import EmailAddress
from .utils import (

class EmailAwarePasswordResetTokenGenerator(PasswordResetTokenGenerator):

    def _make_hash_value(self, user, timestamp):
        ret = super(
            EmailAwarePasswordResetTokenGenerator, self)._make_hash_value(
                user, timestamp)
        emails = set([] if else [])
            .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:
                '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',
        kwargs['widget'] = forms.PasswordInput(render_value=render_value,
        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"),

    user = None
    error_messages = {
        _("This account is currently inactive."),

        _("The e-mail address and/or password you specified are not correct."),

        _("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',
                                                  _('E-mail address'),
                                                  'autofocus': 'autofocus'})
            login_field = forms.EmailField(label=_("E-mail"),
        elif app_settings.AUTHENTICATION_METHOD \
                == AuthenticationMethod.USERNAME:
            login_widget = forms.TextInput(attrs={'placeholder':
                                                  'autofocus': 'autofocus'})
            login_field = forms.CharField(
            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",
        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 ...

Example 3 from django-cms

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 /

# -*- 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_lazy as _,

from cms.admin.forms import AddPageForm
from cms.plugin_pool import plugin_pool
from cms.utils import get_current_site, permissions
from import get_available_slug
from cms.utils.page_permissions import (
from cms.utils.conf import get_cms_setting
from cms.utils.urlutils import static_with_version

    # 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 = (

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.

    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.")

    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.
        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
            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 and self.sub_page_form:
            # User is adding a page which will be a direct
            # child of the current page.
            parent_page =
        elif and
            # User is adding a page which will be a right
            # sibling to the current page.
            parent_page =
            parent_page = None

        if parent_page:
            has_perm = user_can_add_subpage(self.user, target=parent_page)
            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')

    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

        # 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"):
                placeholder = self.get_placeholder(new_page, slot=slot)
                if placeholder:
                    opts = {
                        'placeholder': placeholder,
                        'plugin_type': plugin_type,
                        'language': self.language_code,
                        plugin_body: content,
        return new_page

class CreateCMSSubPageForm(CreateCMSPageForm):

    sub_page_form = True

Example 4 from django-filer

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 /

# -*- 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',
            help_text_html='<p class="help">%s</p>',

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):
            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 ...

Example 5 from django-jet

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 /

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')

            modules = json.loads(data['modules'])

            for module in modules:
                db_module = UserDashboardModule.objects.get(
                    app_label=data['app_label'] if data['app_label'] else None,

                column = module['column']
                order = module['order']

                if db_module.column != column or db_module.order != order:
                    db_module.column = column
                    db_module.order = order

        except Exception:
            raise ValidationError('error')

        return data

    def save(self):
        for module in self.modules_objects:

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']]()
                    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.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 !=
            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 !=
            raise ValidationError('error')

        return cleaned_data

    def save(self, commit=True):
        if commit:

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:

Example 6 from django-mongonaut

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 /

# -*- 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

        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."""

        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)
1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses Django Code Examples django.urls.path django.conf.urls.url django.contrib.admin django.db.models Model django.dispatch Signal django.db.models.signal django.core.mail.send_mail django.core.mail.messages EmailMessage django.conf settings django.forms django.contrib.admin.sites register BaseCommand django.utils.timezone django.contrib.auth get_user_model django.contrib.auth.decorators login_required django.core.exceptions ImproperlyConfigured django.utils.html format_html django.contrib.auth.hashers make_password django.http Http404 django.http HttpResponse django.http HttpResponseForbidden django.http HttpResponseBadRequest django.contrib.admin.filters SimpleListFilter django.urls.exceptions NoReverseMatch django.http HttpResponsePermanentRedirect django.http HttpResponseNotModified django.http HttpResponseRedirect django.apps.config AppConfig django.db OperationalError django.forms BooleanField django.forms CharField django.forms ChoiceField django.forms EmailField flask_sqlalchemy.SQLAlchemy Model django.db.models CharField django.db.models TextField django.db.models BooleanField flask request flask redirect django.db.models DateTimeField django.db.models IntegerField django.forms IntegerField django.db.models AutoField django.db.models DateField django.db.models FileField django.db.models ForeignKey django.db.models SlugField django.template.response TemplateResponse django.template.response SimpleTemplateResponse SQLAlchemy Model Examples django.urls reverse_lazy Flask Core and Extensions Code Examples ...or view the full table of contents.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2019