title: django.forms ChoiceField Python Code Examples
category: page
slug: django-forms-choicefield-examples
sortorder: 500013115
toc: False
sidebartitle: django.forms ChoiceField
meta: Python code examples to show how to use the ChoiceField class within the forms module of the Django open source project. 


The [ChoiceField](https://github.com/django/django/blob/master/django/forms/fields.py)
([documentation](https://docs.djangoproject.com/en/stable/ref/forms/fields/#choicefield))
class in the `django.forms` module in the [Django](/django.html) 
[web framework](/web-frameworks.html) provides a mechanism for safely handling
input from an HTTP POST request. The request is typically generated by an
[HTML](/hypertext-markup-language-html.html) form from the Django
[web application](/web-development.html).


## Example 1 from dccnsys
[dccnsys](https://github.com/dccnconf/dccnsys) is a conference registration
system built with [Django](/django.html). The code is open source under the
[MIT license](https://github.com/dccnconf/dccnsys/blob/master/LICENSE).

[**dccnsys / wwwdccn / chair / forms.py**](https://github.com/dccnconf/dccnsys/blob/master/wwwdccn/chair/forms.py)

```python
# 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'),
]


## ... 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):
        super().__init__(*args)
        self.submission = submission

        # Fill available reviewers - neither already assigned, nor authors:
        reviews = submission.reviews.all()
        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: r.reviews.count())
~~        self.fields['reviewer'].choices = (
~~            (rev.pk,
~~             f'{profiles[rev].get_full_name()} ({rev.reviews.count()}) - '
~~             f'{profiles[rev].affiliation}, '
~~             f'{profiles[rev].get_country_display()}')
~~            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](https://github.com/divio/django-cms)
([project website](https://www.django-cms.org/en/)) is a Python-based
content management system (CMS) [library](https://pypi.org/project/django-cms/)
for use with Django web apps that is open sourced under the
[BSD 3-Clause "New"](https://github.com/divio/django-cms/blob/develop/LICENSE)
license.

[**django-cms / cms / forms / fields.py**](https://github.com/divio/django-cms/blob/develop/cms/forms/fields.py)

```python
# -*- 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](https://github.com/geex-arts/django-jet)
([project documentation](https://jet.readthedocs.io/en/latest/),
[PyPI project page](https://pypi.org/project/django-jet/) and
[more information](http://jet.geex-arts.com/))
is a fancy [Django](/django.html) Admin panel replacement.

The django-jet project is open source under the
[GNU Affero General Public License v3.0](https://github.com/geex-arts/django-jet/blob/dev/LICENSE).

[**django-jet / jet / dashboard / modules.py**](https://github.com/geex-arts/django-jet/blob/dev/jet/dashboard/modules.py)

```python
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](https://github.com/jazzband/django-mongonaut)
([project documentation](https://django-mongonaut.readthedocs.io/en/latest/)
and
[PyPI package information](https://pypi.org/project/django-mongonaut/))
provides an introspective interface for working with
[MongoDB](/mongodb.html) via mongoengine. The project has its own new code
to map MongoDB to the [Django](/django.html) 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](https://github.com/jazzband/django-mongonaut/blob/master/LICENSE.txt)
and it is maintained by the developer community group
[Jazzband](https://jazzband.co/).

[**django-mongonaut / mongonaut / forms / form_mixins.py**](https://github.com/jazzband/django-mongonaut/blob/master/mongonaut/forms/form_mixins.py)

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

try:
    # 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."""
    try:
        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 forms.py for an example.
    """

    def __init__(self, model, instance=None, form_post_data=None):
        """
        Params:
            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(label=model_field.name,
~~                                                            required=model_field.required,
~~                                                            widget=widget)
        else:
            field_class = get_form_field_class(model_field)
            self.form.fields[field_key] = field_class(label=model_field.name,
                                                      required=model_field.required,
                                                      widget=widget)

        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)
            else:
                self.form.fields[field_key].initial = default_value
        else:
            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(x.id), 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
                else:
                    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)
            else:
                # Handeling all other fields and id
                try: # Added try except otherwise we get "TypeError: getattr(): attribute name must be string" error from mongoengine/base/datastructures.py 
                    return_data = (document._data.get(None, None) if current_key == "id" else
                              document._data.get(current_key, None))
                except: 
                    return_data = document._data.get(current_key, None)

            return return_data

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

```


## Example 5 from wagtail
[wagtail](https://github.com/wagtail/wagtail)
([project website](https://wagtail.io/)) is a fantastic
[Django](/django.html)-based CMS with code that is open source
under the
[BSD 3-Clause "New" or "Revised" License](https://github.com/wagtail/wagtail/blob/master/LICENSE).

[**wagtail / wagtail / images / forms.py**](https://github.com/wagtail/wagtail/blob/master/wagtail/images/forms.py)

```python
# forms.py
~~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 db_field.name == '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(
        model,
        form=BaseImageForm,
        fields=fields,
        formfield_callback=formfield_for_dbfield,
        # 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
        widgets={
            '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.name, format.label) for format in get_image_formats()],
~~        widget=forms.RadioSelect
~~    )
~~    alt_text = forms.CharField()


class URLGeneratorForm(forms.Form):
~~    filter_method = forms.ChoiceField(
~~        label=_("Filter"),
~~        choices=(
~~            ('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(
    Image,
    [
        ('add_image', _("Add"), _("Add/edit images you own")),
        ('change_image', _("Edit"), _("Edit any image")),
    ],
    'wagtailimages/permissions/includes/image_permissions_formset.html'
)

```


