django.forms ChoiceField Python Code Examples

The ChoiceField (documentation) class in the django.forms module in the Django web framework provides a mechanism for safely handling input from an HTTP POST request. The request is typically generated by an HTML form from the Django 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'),

## ... source file abbreviated to get to ChoiceField example ...

class AssignReviewerForm(forms.Form):
    reviewer = forms.ChoiceField(required=True, label=_('Assign reviewer'))

    def __init__(self, *args, submission=None):
        self.submission = submission

        # Fill available reviewers - neither already assigned, nor authors:
        reviews =
        assigned_reviewers = reviews.values_list('reviewer', flat=True)
        authors_users = submission.authors.values_list('user', flat=True)
        available_reviewers = Reviewer.objects.exclude(
            Q(pk__in=assigned_reviewers) | Q(user__in=authors_users)
        profiles = {
            rev: rev.user.profile for rev in available_reviewers
        reviewers = list(available_reviewers)
        reviewers.sort(key=lambda r:
        self.fields['reviewer'].choices = (
             f'{profiles[rev].get_full_name()} ({}) - '
             f'{profiles[rev].affiliation}, '
            for rev in reviewers

   def save(self):
       reviewer = Reviewer.objects.get(pk=self.cleaned_data['reviewer'])
       review = Review.objects.create(reviewer=reviewer, paper=self.submission)
       return review

Example 2 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 django import forms
from django.contrib.admin.widgets import RelatedFieldWidgetWrapper
from django.forms.fields import EMPTY_VALUES
from django.utils.translation import ugettext_lazy as _

from cms.forms.utils import get_site_choices, get_page_choices
from cms.forms.validators import validate_url
from cms.forms.widgets import PageSelectWidget, PageSmartLinkWidget
from cms.models.pagemodel import Page

class SuperLazyIterator(object):
    def __init__(self, func):
        self.func = func

    def __iter__(self):
        return iter(self.func())

class LazyChoiceField(forms.ChoiceField):
    def _set_choices(self, value):
        # we overwrite this function so no list(value) is called
        self._choices = self.widget.choices = value

   choices = property(forms.ChoiceField._get_choices, _set_choices)

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

Example 3 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.contrib.admin.models import LogEntry
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from jet.utils import get_app_list, LazyDateTimeEncoder, context_to_dict
import datetime

## ... source file abbreviated to get to the ChoiceField examples ...

class LinkListSettingsForm(forms.Form):
    layout = forms.ChoiceField(label=_('Layout'), 
                               choices=(('stacked', _('Stacked')), 
                                        ('inline', _('Inline'))))

## ... no further ChoiceField examples in this source file ..

Example 4 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 -*-

import six
from copy import deepcopy

from django import forms
from mongoengine.base import BaseList
from mongoengine.base import TopLevelDocumentMetaclass
from mongoengine.fields import Document
from mongoengine.fields import EmbeddedDocumentField
from mongoengine.fields import ListField
from mongoengine.fields import ReferenceField

from .form_utils import FieldTuple
from .form_utils import has_digit
from .form_utils import make_key
from .widgets import get_form_field_class
from mongonaut.utils import trim_field_key

    # OrderedDict New in version 2.7
    from collections import OrderedDict
except ImportError:
    OrderedDict = dict

CHECK_ATTRS = {'required': 'required',
               'help_text': 'help_text',
               'name': 'name'}

def get_document_unicode(document):
    """Safely converts MongoDB document strings to unicode."""
        return document.__unicode__()
    except AttributeError:
        return six.text_type(document)

class MongoModelFormBaseMixin(object):
    For use with mongoengine.

    This mixin should not be used alone it should be used to inherit from.

    This mixin provides functionality for generating a form.  Provides 4 methods
    useful for putting data on a form:

    get_form_field_dict -- creates a keyed tuple representation of a model field used
                           to create form fields
    set_form_fields -- takes the form field dictionary and sets all values on a form
    set_form_field -- sets an individual form field
    get_field_value -- returns the value for the field

    If you inherit from this class you will need to call the above methods
    with the correct values, see for an example.

    def __init__(self, model, instance=None, form_post_data=None):
            model          -- The model class to create the form with
            instance       -- An instance of the model class can be used to
                              initialize data.
            form_post_data -- Values given by request.POST
        self.model = model
        self.model_instance = instance
        self.post_data_dict = form_post_data
        # Preferred for symantic checks of model_instance
        self.is_initialized = False if instance is None else True
        self.form = forms.Form()

## ... source file abbreviated to get to the ChoiceField examples ...

        if widget and isinstance(widget, forms.widgets.Select):
            self.form.fields[field_key] = forms.ChoiceField(,
            field_class = get_form_field_class(model_field)
            self.form.fields[field_key] = field_class(,

        if default_value is not None:
            if isinstance(default_value, Document):
                # Probably a reference field, therefore, add id
                self.form.fields[field_key].initial = getattr(default_value, 'id', None)
                self.form.fields[field_key].initial = default_value
            self.form.fields[field_key].initial = getattr(model_field, 'default', None)

        if isinstance(model_field, ReferenceField):
            self.form.fields[field_key].choices = [(six.text_type(, get_document_unicode(x))
                                                    for x in model_field.document_type.objects.all()]
            # Adding in blank choice so a reference field can be deleted by selecting blank
            self.form.fields[field_key].choices.insert(0, ("", ""))

        elif model_field.choices:
            self.form.fields[field_key].choices = model_field.choices

        for key, form_attr in CHECK_ATTRS.items():
            if hasattr(model_field, key):
                value = getattr(model_field, key)
                setattr(self.form.fields[field_key], key, value)

    def get_field_value(self, field_key):
        Given field_key will return value held at self.model_instance.  If
        model_instance has not been provided will return None.

        def get_value(document, field_key):
            # Short circuit the function if we do not have a document
            if document is None:
                return None

            current_key, new_key_array = trim_field_key(document, field_key)
            key_array_digit = int(new_key_array[-1]) if new_key_array and has_digit(new_key_array) else None
            new_key = make_key(new_key_array)

            if key_array_digit is not None and len(new_key_array) > 0:
                # Handleing list fields
                if len(new_key_array) == 1:
                    return_data = document._data.get(current_key, [])
                elif isinstance(document, BaseList):
                    return_list = []
                    if len(document) > 0:
                        return_list = [get_value(doc, new_key) for doc in document]
                    return_data = return_list
                    return_data = get_value(getattr(document, current_key), new_key)

            elif len(new_key_array) > 0:
                return_data = get_value(document._data.get(current_key), new_key)
                # Handeling all other fields and id
                try: # Added try except otherwise we get "TypeError: getattr(): attribute name must be string" error from mongoengine/base/ 
                    return_data = (document._data.get(None, None) if current_key == "id" else
                              document._data.get(current_key, None))
                    return_data = document._data.get(current_key, None)

            return return_data

        if self.is_initialized:
            return get_value(self.model_instance, field_key)
            return None

Example 5 from wagtail

wagtail (project website) is a fantastic Django-based CMS with code that is open source under the BSD 3-Clause "New" or "Revised" License.

wagtail / wagtail / images /

from django import forms
from django.forms.models import modelform_factory
from django.utils.text import capfirst
from django.utils.translation import ugettext as _

from wagtail.admin import widgets
from wagtail.admin.forms.collections import (
    BaseCollectionMemberForm, collection_member_permission_formset_factory)
from wagtail.images.fields import WagtailImageField
from wagtail.images.formats import get_image_formats
from wagtail.images.models import Image
from wagtail.images.permissions import permission_policy as images_permission_policy

# Callback to allow us to override the default form field for the image file field
def formfield_for_dbfield(db_field, **kwargs):
    # Check if this is the file field
    if == 'file':
        return WagtailImageField(label=capfirst(db_field.verbose_name), **kwargs)

    # For all other fields, just call its formfield() method.
    return db_field.formfield(**kwargs)

class BaseImageForm(BaseCollectionMemberForm):
    permission_policy = images_permission_policy

def get_image_form(model):
    fields = model.admin_form_fields
    if 'collection' not in fields:
        # force addition of the 'collection' field, because leaving it out can
        # cause dubious results when multiple collections exist (e.g adding the
        # document to the root collection where the user may not have permission) -
        # and when only one collection exists, it will get hidden anyway.
        fields = list(fields) + ['collection']

    return modelform_factory(
        # set the 'file' widget to a FileInput rather than the default ClearableFileInput
        # so that when editing, we don't get the 'currently: ...' banner which is
        # a bit pointless here
            'tags': widgets.AdminTagWidget,
            'file': forms.FileInput(),
            'focal_point_x': forms.HiddenInput(attrs={'class': 'focal_point_x'}),
            'focal_point_y': forms.HiddenInput(attrs={'class': 'focal_point_y'}),
            'focal_point_width': forms.HiddenInput(attrs={'class': 'focal_point_width'}),
            'focal_point_height': forms.HiddenInput(attrs={'class': 'focal_point_height'}),

class ImageInsertionForm(forms.Form):
    Form for selecting parameters of the image (e.g. format) prior to insertion
    into a rich text area
    format = forms.ChoiceField(
        choices=[(, format.label) for format in get_image_formats()],
    alt_text = forms.CharField()

class URLGeneratorForm(forms.Form):
    filter_method = forms.ChoiceField(
            ('original', _("Original size")),
            ('width', _("Resize to width")),
            ('height', _("Resize to height")),
            ('min', _("Resize to min")),
            ('max', _("Resize to max")),
            ('fill', _("Resize to fill")),
    width = forms.IntegerField(label=_("Width"), min_value=0)
    height = forms.IntegerField(label=_("Height"), min_value=0)
    closeness = forms.IntegerField(label=_("Closeness"), min_value=0, initial=0)

GroupImagePermissionFormSet = collection_member_permission_formset_factory(
        ('add_image', _("Add"), _("Add/edit images you own")),
        ('change_image', _("Edit"), _("Edit any image")),
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 ExtensionsDjango Example Codedjango.apps.config AppConfigdjango.conf settingsdjango.conf.urls.urldjango.contrib.admindjango.contrib.admin.filters SimpleListFilterdjango.contrib.admin.sites registerdjango.contrib.auth.decorators login_requireddjango.contrib.auth get_user_modeldjango.contrib.auth.hashers make_passworddjango.core.exceptions ImproperlyConfigureddjango.core.mail.messages BaseCommanddjango.db.models AutoFielddjango.db.models BooleanFielddjango.db.models CharFielddjango.db.models DateFielddjango.db.models DateTimeFielddjango.db.models FileFielddjango.db.models ForeignKeydjango.db.models GenericIPAddressFielddjango.db.models ImageFielddjango.db.models IntegerFielddjango.db.models Modeldjango.db.models PositiveIntegerFielddjango.db.models PositiveSmallIntegerFielddjango.db.models.signaldjango.db.models SlugFielddjango.db.models SmallIntegerFielddjango.db.models TextFielddjango.db OperationalErrordjango.dispatch Signaldjango.formsdjango.forms BooleanFielddjango.forms CharFielddjango.forms ChoiceFielddjango.forms EmailFielddjango.forms IntegerFielddjango.http Http404django.http HttpResponsedjango.http HttpResponseBadRequestdjango.http HttpResponseForbiddendjango.http HttpResponseNotModifieddjango.http HttpResponsePermanentRedirectdjango.http HttpResponseRedirectdjango.template.response SimpleTemplateResponsedjango.template.response TemplateResponsedjango.urls.pathdjango.urls reverse_lazydjango.urls.exceptions NoReverseMatchdjango.urls.exceptions Resolver404django.utils.html format_htmldjango.utils.timezone ...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-2020