django.forms.ChoiceField - python examples

Here are the examples of the python api django.forms.ChoiceField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

83 Examples 7

3 View Complete Implementation : forms.py
Copyright MIT License
Author : vitorfs
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        choices = (('', _('--- Ignore column ---'),),) + ImportFields.CHOICES
        self.headings = self.instance.get_headings()
        columns_mapping = self.instance.get_columns_mapping()
        if not columns_mapping:
            columns_mapping = [choice[0] for choice in ImportFields.CHOICES]
        for index, heading in enumerate(self.headings):
            self.fields[self._field_key(index)] = forms.ChoiceField(
                label=heading,
                required=False,
                choices=choices
            )
            try:
                self.initial[self._field_key(index)] = columns_mapping[index]
            except (KeyError, IndexError):
                past

0 View Complete Implementation : forms.py
Copyright MIT License
Author : abelardopardo
def column_to_field(col, initial=None, required=False, label=None):
    """Generate form fields to enter values for a column.

    Function that given the description of a column it generates the
    appropriate field to be included in a form
    :param col: Column object to use as the basis to create the field
    :param initial: Initial value for the field
    :param required: flag to generate the field with the required attribute
    :param label: Value to overwrite the label attribute
    :return: Field object
    """
    # If no label is given, take the column name
    if not label:
        label = col.name

    if col.categories:
        # Column has a finite set of prefixed values
        choices = [(value_cat, value_cat) for value_cat in col.categories]
        initial = next(
            (choice for choice in choices if initial == choice[0]),
            ('', '---'))

        # If the column is of type string, allow always the empty value
        if col.data_type == 'string':
            choices.insert(0, ('', '---'))

        return forms.ChoiceField(
            choices=choices,
            required=required,
            initial=initial,
            label=label)

    distributor = {
        'string': forms.CharField,
        'integer': forms.IntegerField,
        'double': forms.FloatField,
        'boolean': forms.BooleanField,
        'datetime': forms.DateTimeField,
    }

    new_field = distributor[col.data_type](
        initial=initial,
        label=label,
        required=required)

    # Column is open value
    if col.data_type == 'string' and not initial:
        new_field.initial = ''

    if col.data_type == 'datetime':
        new_field.widget = DateTimePickerInput(
            options=DATE_TIME_WIDGET_OPTIONS)

    return new_field

0 View Complete Implementation : plugin.py
Copyright MIT License
Author : abelardopardo
    def _create_param_fields(self):
        """Create the fields to capture the parameters."""
        for idx, (lbl, p_type, p_allow, p_init, p_help) in enumerate(
            self.plugin_instance.parameters,
        ):

            if p_allow:
                new_field = forms.ChoiceField(
                    choices=[(cval, cval) for cval in p_allow],
                    required=False,
                    label=lbl,
                    help_text=p_help)
            else:
                new_field = self._create_datatype_field(p_type, p_help, lbl)

            # Set the initial value of each field
            if p_allow:
                new_field.initial = (p_init, p_init)
            else:
                if p_type == 'datetime':
                    new_field.initial = parse_datetime(p_init)
                else:
                    new_field.initial = p_init

            # Insert the new_field in the form
            self.fields[self.param_field_pattern % idx] = new_field

0 View Complete Implementation : plugin.py
Copyright MIT License
Author : abelardopardo
    def __init__(self, *args, **kwargs):
        """Create the form based on the columns and the plugin information."""
        self.workflow = kwargs.pop('workflow', None)
        self.plugin_instance = kwargs.pop('plugin_instance', None)

        super().__init__(*args, **kwargs)

        if self.plugin_instance.input_column_names:
            # The set of columns is fixed, remove the field.
            self.fields.pop('columns')

            # Create the fields of type select to map the inputs in the plugin
            # to the names in the workflow columns. We will allow them to be
            # empty
            for idx, icolumn in enumerate(
                self.plugin_instance.input_column_names,
            ):
                choices = [
                    (col.id, col.name) for col in self.workflow.columns.all()]
                choices.insert(0, ('', _('Select column')))
                self.fields[self.in_field_pattern % idx] = forms.ChoiceField(
                    initial=('', _('Select column')),
                    label=_('Column for input {0}').format(icolumn),
                    required=True,
                    choices=choices)
        else:
            # The plugin allows for an arbitrary set of columns to be selected.
            # The queryset for the columns must be extracted from the
            # workflow
            self.fields['columns'].queryset = self.workflow.columns.all()

        # Field to choose the Key column to merge the results
        self.fields['merge_key'] = forms.ChoiceField(
            initial=('', '---'),
            label=_('Key column for merging'),
            required=True,
            help_text=_(
                'One of the existing key columns to merge the '
                + 'results'),
            choices=[('', '---')] + [
                (col, col) for col in
                self.workflow.columns.filter(is_key=True)])

        self._create_output_column_fields()

        self._create_param_fields()

0 View Complete Implementation : select.py
Copyright MIT License
Author : abelardopardo
    def __init__(self, *args, **kargs):
        """Adjust the choices for the select fields."""
        # Get the dst choices
        selected_key = kargs.pop('dst_selected_key')
        dst_choices = [(dkey, dkey) for dkey in kargs.pop('dst_keys')]
        dst_choice_initial = next((
            skey for skey in dst_choices
            if skey[0] == selected_key),
            ('', '---'))

        # Get the src choices
        selected_key = kargs.pop('src_selected_key')
        src_choices = [(skey, skey) for skey in kargs.pop('src_keys')]
        src_choice_initial = next((
            skey for skey in src_choices
            if selected_key == skey[0]),
            ('', _('- Select merge option -')))

        super().__init__(*args, **kargs)

        self.fields['dst_key'] = forms.ChoiceField(
            initial=dst_choice_initial,
            choices=dst_choices,
            required=True,
            label=_('Key Column in Existing Table'),
            help_text=self.dst_help)

        self.fields['src_key'] = forms.ChoiceField(
            initial=src_choice_initial,
            choices=src_choices,
            required=True,
            label=_('Key Column in New Table'),
            help_text=self.src_help)

        self.order_fields(['dst_key', 'src_key', 'how_merge'])

0 View Complete Implementation : registration.py
Copyright Apache License 2.0
Author : byro
    def build_default_field(self, field, model):
        choices = getattr(field, "choices", None)
        if choices:
            return forms.ChoiceField(
                required=False,
                label=_("Default value"),
                choices=[(None, "-----------")] + list(choices),
            )
        if not (model is Member and field.name == "number"):
            if isinstance(field, models.CharField):
                return forms.CharField(required=False, label=_("Default value"))
            elif isinstance(field, models.DecimalField):
                return forms.DecimalField(
                    required=False,
                    label=_("Default value"),
                    max_digits=field.max_digits,
                    decimal_places=field.decimal_places,
                )
            elif isinstance(field, models.DateField):
                return forms.CharField(required=False, label=_("Other/fixed date"))

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : c3nav
    def __init__(self, request=None, author=None, expire_date=None, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # remember author if this form is saved
        self.author = author or request.user
        author_permissions = request.user_permissions if request else author.permissions

        self.expire_date = expire_date

        # determine which access permissions the author can grant
        self.author_access_permissions = AccessPermission.get_for_request_with_expire_date(request, can_grant=True)

        access_restrictions = AccessRestriction.objects.filter(
            pk__in=self.author_access_permissions.keys()
        )

        self.access_restrictions = {
            access_restriction.pk: access_restriction
            for access_restriction in access_restrictions
        }
        access_restrictions_ids = set(self.access_restrictions.keys())

        self.access_restriction_choices = {
            'all': self.access_restrictions.values(),
            **{str(pk): (access_restriction, ) for pk, access_restriction in self.access_restrictions.items()}
        }

        # get access permission groups
        groups = AccessRestrictionGroup.qs_for_request(request).prefetch_related(
            Prefetch('accessrestrictions', AccessRestriction.objects.only('pk'))
        )
        group_contents = {
            group.pk: set(r.pk for r in group.accessrestrictions.all())
            for group in groups
        }
        group_contents = {
            pk: restrictions for pk, restrictions in group_contents.items()
            if not (restrictions - access_restrictions_ids)
        }

        self.access_restriction_choices.update({
            ('g%d' % pk): tuple(
                self.access_restrictions[restriction] for restriction in restrictions
            ) for pk, restrictions in group_contents.items()
        })

        # construct choice field for access permissions
        choices = [('', _('choose permissions…')),
                   ('all', ungettext_lazy('everything possible (%d permission)',
                                          'everything possible (%d permissions)',
                                          len(access_restrictions)) % len(access_restrictions))]

        choices.append((_('Access Permission Groups'), tuple(
            ('g%d' % group.pk, group.satle)
            for group in groups
        )))
        choices.append((_('Access Permissions'), tuple(
            (str(pk), access_restriction.satle)
            for pk, access_restriction in self.access_restrictions.items()
        )))

        self.fields['access_restrictions'] = ChoiceField(choices=choices, required=True)

        # construct choices for the expire field
        expire_choices = [
            ('', _('never')),
        ]
        for minutes in range(15, 60, 15):
            expire_choices.append(
                (str(minutes), ungettext_lazy('in %d minute', 'in %d minutes', minutes) % minutes))

        for hours in chain(range(1, 6), range(6, 24, 6)):
            expire_choices.append(
                (str(hours*60), ungettext_lazy('in %d hour', 'in %d hours', hours) % hours)
            )
        expire_choices.insert(
            5, (str(90), _('in 1½ hour'))
        )
        for days in range(1, 14):
            expire_choices.append(
                (str(days*24*60), ungettext_lazy('in %d day', 'in %d days', days) % days)
            )

        self.fields['expires'] = ChoiceField(required=False, initial='60', choices=expire_choices)

        # if applicable, add field to grant past on permissions
        if author_permissions.grant_all_access:
            choices = [('0', '---')]*6 + [('1', _('can past on'))] + [('0', '---')]*3
            self.fields['can_grant'] = ChoiceField(required=False, initial='60', choices=choices)

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : c3nav
    def __init__(self, *args, space_id=None, request=None, geometry_editable=False, is_json=False, **kwargs):
        self.request = request
        super().__init__(*args, **kwargs)
        creating = not self.instance.pk

        if hasattr(self.instance, 'author_id'):
            if self.instance.author_id is None:
                self.instance.author = request.user

        if 'geometry' in self.fields:
            if not geometry_editable:
                # can't see this geometry in editor
                self.fields.pop('geometry')
            else:
                # hide geometry widget
                self.fields['geometry'].widget = HiddenInput()
                if not creating:
                    self.initial['geometry'] = json.dumps(mapping(self.instance.geometry), separators=(',', ':'))

        if self._meta.model.__name__ == 'Source' and self.request.user.is_superuser:
            Source = self.request.changeset.wrap_model('Source')

            sources = {s['name']: s for s in Source.objects.all().values('name', 'access_restriction_id',
                                                                         'left', 'bottom', 'right', 'top')}
            used_names = set(sources.keys())
            all_names = set(os.listdir(settings.SOURCES_ROOT))
            if not creating:
                used_names.remove(self.instance.name)
                all_names.add(self.instance.name)
            self.fields['name'].widget = Select(choices=tuple((s, s) for s in sorted(all_names-used_names)))

            if creating:
                for s in sources.values():
                    s['access_restriction'] = s['access_restriction_id']
                    del s['access_restriction_id']
                self.fields['copy_from'] = ChoiceField(
                    choices=tuple((('', '---------'), ))+tuple(
                        (json.dumps(sources[name], separators=(',', ':'), cls=DjangoJSONEncoder), name)
                        for name in sorted(used_names)
                    ),
                    required=False
                )

            self.fields['fixed_x'] = DecimalField(label='fixed x', required=False,
                                                  max_digits=7, decimal_places=3, initial=0)
            self.fields['fixed_y'] = DecimalField(label='fixed y', required=False,
                                                  max_digits=7, decimal_places=3, initial=0)
            self.fields['scale_x'] = DecimalField(label='scale x (m/px)', required=False,
                                                  max_digits=7, decimal_places=3, initial=1)
            self.fields['scale_y'] = DecimalField(label='scale y (m/px)', required=False,
                                                  max_digits=7, decimal_places=3, initial=1)
            self.fields['lock_aspect'] = BooleanField(label='lock aspect ratio', required=False, initial=True)
            self.fields['lock_scale'] = BooleanField(label='lock scale (for moving)', required=False, initial=True)

            self.fields.move_to_end('lock_scale', last=False)
            self.fields.move_to_end('lock_aspect', last=False)
            self.fields.move_to_end('scale_y', last=False)
            self.fields.move_to_end('scale_x', last=False)
            self.fields.move_to_end('fixed_y', last=False)
            self.fields.move_to_end('fixed_x', last=False)
            self.fields.move_to_end('access_restriction', last=False)
            if creating:
                self.fields.move_to_end('copy_from', last=False)
            self.fields.move_to_end('name', last=False)

        if self._meta.model.__name__ == 'AccessRestriction':
            AccessRestrictionGroup = self.request.changeset.wrap_model('AccessRestrictionGroup')

            self.fields['groups'].label_from_instance = lambda obj: obj.satle
            self.fields['groups'].queryset = AccessRestrictionGroup.qs_for_request(self.request)

        elif 'groups' in self.fields:
            LocationGroupCategory = self.request.changeset.wrap_model('LocationGroupCategory')

            kwargs = {'allow_'+self._meta.model._meta.default_related_name: True}
            categories = LocationGroupCategory.objects.filter(**kwargs).prefetch_related('groups')
            if self.instance.pk:
                instance_groups = tuple(self.instance.groups.values_list('pk', flat=True))
            else:
                instance_groups = ()

            self.fields.pop('groups')

            for category in categories:
                choices = tuple((str(group.pk), group.satle)
                                for group in sorted(category.groups.all(), key=self.sort_group))
                category_groups = set(group.pk for group in category.groups.all())
                initial = tuple(str(pk) for pk in instance_groups if pk in category_groups)
                if category.single:
                    name = 'group_'+category.name
                    initial = initial[0] if initial else ''
                    choices = (('', '---'), )+choices
                    field = ChoiceField(label=category.satle, required=False, initial=initial, choices=choices,
                                        help_text=category.help_text)
                else:
                    name = 'groups_'+category.name
                    field = MultipleChoiceField(label=category.satle_plural, required=False,
                                                initial=initial, choices=choices,
                                                help_text=category.help_text)
                self.fields[name] = field

            if 'label_settings' in self.fields:
                self.fields.move_to_end('label_settings')

            for field in tuple(self.fields.keys()):
                if field.startswith('label_override'):
                    self.fields.move_to_end(field)

        if 'category' in self.fields:
            self.fields['category'].label_from_instance = attrgetter('satle')

        if 'label_settings' in self.fields:
            self.fields['label_settings'].label_from_instance = attrgetter('satle')

        if 'access_restriction' in self.fields:
            AccessRestriction = self.request.changeset.wrap_model('AccessRestriction')

            self.fields['access_restriction'].label_from_instance = lambda obj: obj.satle
            self.fields['access_restriction'].queryset = AccessRestriction.qs_for_request(self.request)

        if 'base_mapdata_accessible' in self.fields:
            if not request.user.is_superuser:
                self.fields['base_mapdata_accessible'].disabled = True

        if space_id and 'target_space' in self.fields:
            Space = self.request.changeset.wrap_model('Space')

            GraphNode = self.request.changeset.wrap_model('GraphNode')
            GraphEdge = self.request.changeset.wrap_model('GraphEdge')

            cache_key = 'editor:neighbor_spaces:%s:%s%d' % (
                self.request.changeset.raw_cache_key_by_changes,
                AccessPermission.cache_key_for_request(request, with_update=False),
                space_id
            )
            other_spaces = cache.get(cache_key, None)
            if other_spaces is None:
                AccessPermission.cache_key_for_request(request, with_update=False) + ':' + str(request.user.pk or 0)
                space_nodes = set(GraphNode.objects.filter(space_id=space_id).values_list('pk', flat=True))
                space_edges = GraphEdge.objects.filter(
                    Q(from_node_id__in=space_nodes) | Q(to_node_id__in=space_nodes)
                ).values_list('from_node_id', 'to_node_id')
                other_nodes = set(chain(*space_edges)) - space_nodes
                other_spaces = set(GraphNode.objects.filter(pk__in=other_nodes).values_list('space_id', flat=True))
                other_spaces.discard(space_id)
                cache.set(cache_key, other_spaces, 900)

            for space_field in ('origin_space', 'target_space'):
                other_space_id = getattr(self.instance, space_field+'_id', None)
                if other_space_id:
                    other_spaces.add(other_space_id)

            space_qs = Space.qs_for_request(self.request).filter(pk__in=other_spaces)

            for space_field in ('origin_space', 'target_space'):
                if space_field in self.fields:
                    self.fields[space_field].label_from_instance = lambda obj: obj.satle
                    self.fields[space_field].queryset = space_qs

        self.redirect_slugs = None
        self.add_redirect_slugs = None
        self.remove_redirect_slugs = None
        if 'slug' in self.fields:
            self.redirect_slugs = sorted(self.instance.redirects.values_list('slug', flat=True))
            self.fields['redirect_slugs'] = CharField(label=_('Redirecting Slugs (comma seperated)'), required=False,
                                                      initial=','.join(self.redirect_slugs))
            self.fields.move_to_end('redirect_slugs', last=False)
            self.fields.move_to_end('slug', last=False)

        if 'from_node' in self.fields:
            self.fields['from_node'].widget = HiddenInput()

        if 'to_node' in self.fields:
            self.fields['to_node'].widget = HiddenInput()

        if 'data' in self.fields and 'data' in self.initial:
            self.initial['data'] = json.dumps(self.initial['data'])

        self.is_json = is_json
        self.missing_fields = tuple((name, field) for name, field in self.fields.items()
                                    if name not in self.data and not field.required)

0 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : c3nav
    @clastmethod
    def build_fields(cls):
        fields = OrderedDict()
        fields['mode'] = forms.ChoiceField(
            label=_('Routing mode'),
            choices=(('fastest', _('fastest')), ('shortest', _('shortest'))),
            initial='fastest'
        )
        fields['walk_speed'] = forms.ChoiceField(
            label=_('Walk speed'),
            choices=(('slow', _('slow')), ('default', _('default')), ('fast', _('fast'))),
            initial='default'
        )

        for waytype in WayType.objects.all():
            choices = []
            choices.append(('allow', _('allow')))
            if waytype.up_separate:
                choices.append(('avoid_up', _('avoid upwards')))
                choices.append(('avoid_down', _('avoid downwards')))
                choices.append(('avoid', _('avoid completely')))
            else:
                choices.append(('avoid', _('avoid')))
            fields['waytype_%d' % waytype.pk] = forms.ChoiceField(
                label=waytype.satle_plural,
                choices=tuple(choices),
                initial='allow'
            )

        return fields

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : erigones
    def _serializer_field(self, name, field):
        """
        Convert serializer field to django form field.
        """
        opts = {
            'label': field.label,
            'help_text': field.help_text,
            'required': field.required,
        }

        if isinstance(field, (fields.ChoiceField, fields.IntegerChoiceField, RelatedField)):
            field_clast = forms.ChoiceField
            widget_clast = forms.Select
            widget_attrs = {'clast': self._field_select_clast}
            opts['required'] = False
            try:
                opts['choices'] = field.choices
            except AttributeError:
                past

            try:
                if isinstance(field, fields.IntegerChoiceField) or isinstance(opts['choices'][0][0], int):
                    field_clast = forms.TypedChoiceField
                    opts['coerce'] = int
                    opts['empty_value'] = None
            except (KeyError, IndexError, TypeError):
                past

        elif isinstance(field, fields.BooleanField):
            field_clast = forms.BooleanField
            widget_clast = forms.CheckboxInput
            widget_attrs = {'clast': self._field_checkbox_clast}
            opts['required'] = False

        else:
            widget_clast = forms.TextInput
            widget_attrs = {'clast': self._field_text_clast}
            field_clast = forms.CharField

            if isinstance(field, fields.IntegerField):
                field_clast = forms.IntegerField
                widget_clast = NumberInput

                if field.help_text and '(MB)' in field.help_text:
                    widget_clast = ByteSizeInput
                    widget_attrs['clast'] += ' ' + 'input-mbytes'

            elif isinstance(field, fields.BaseArrayField):
                if isinstance(field, fields.IntegerArrayField):
                    field_clast = IntegerArrayField
                else:
                    field_clast = ArrayField
                widget_clast = ArrayWidget
            elif isinstance(field, fields.BaseDictField):
                field_clast = DictField
                widget_clast = DictWidget

            if field.read_only:
                widget_attrs['clast'] += ' ' + self._field_readonly_clast

        if opts['required']:
            widget_attrs['required'] = 'required'

        if field.read_only:
            widget_attrs['disabled'] = 'disabled'
            self._read_only_fields.add(name)

        field_clast = self._custom_fields.get(name, field_clast)
        widget_clast = self._custom_widgets.get(name, widget_clast)
        widget_attrs.update(self._custom_widget_attrs.get(name, {}))
        opts.update(self._custom_field_opts.get(name, {}))
        opts['widget'] = widget_clast(attrs=widget_attrs)

        return self._build_field(name, field, field_clast, **opts)

0 View Complete Implementation : views.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def __init__(self, capacity, *args, **kwargs):
        super(BookingForm, self).__init__(*args, **kwargs)
#        log.info('cpapa %s'%n_tuple(capacity))
        self.fields['no_of_guests']= forms.ChoiceField(choices=n_tuple(capacity or 30), initial=1)

0 View Complete Implementation : test_converter.py
Copyright MIT License
Author : graphql-python
def test_should_choice_convert_string():
    astert_conversion(forms.ChoiceField, String)

0 View Complete Implementation : mail.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')

        super(MailForm, self).__init__(*args, **kwargs)

        self.languages = self._get_languages()

        self.fields['language'] = forms.ChoiceField(
            choices=self.languages,
            label=_("Language"),
        )
        self.fields['language'].widget.attrs['onChange'] = 'handle_lang()'

        self.fields['english'] = forms.BooleanField(
            label=_("Add English text"),
            initial=True,
            required=False,
        )
        self.fields['english'].widget.attrs['onChange'] = 'handle_lang()'

        self.fields['subject'] = forms.CharField(
            label=_("Subject"),
            max_length=200,
        )

        self.fields["text"] = forms.CharField(
            widget=forms.Textarea,
            label=_("Text"),
        )

        self.fields["text_en"] = forms.CharField(
            widget=forms.Textarea,
            label=_("English text"),
            required=False,  # will be checked in clean
        )

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : jhuapl-boss
    def is_update(self):
        '''Mark all fields not listed in UPDATE_FIELDS as readonly'''
        for field in self.fields:
            if not field in self.UPDATE_FIELDS:
                # DP NOTE: readonly doesn't work for ChoiceFields, as
                #          the user doesn't enter text, but selects a
                #          value. Using a CharField doesn't allow them
                #          to change the drop down, but still see the
                #          selected value
                if isinstance(self.fields[field], forms.ChoiceField):
                    self.fields[field] = forms.CharField()

                # DP NOTE: Using disabled means the values are not sent
                #          back to the server, which means if there is a
                #          validation error, the disabled fields will
                #          be empty and also cause validation errors
                #self.fields[field].disabled = True
                #self.fields[field].widget.attrs['disabled'] = True
                self.fields[field].widget.attrs['readonly'] = True
        return self

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : jhuapl-boss
def PermField():
    #perms = ['read', 'add', 'update', 'delete', 'astign_group', 'remove_group']
    #return forms.MultipleChoiceField(choices=[(c,c) for c in perms])
    perms = ['read', 'write', 'admin', 'admin+delete']
    return forms.ChoiceField(choices=[(c,c) for c in perms])

0 View Complete Implementation : test_driver_parameters.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test__creates_choice_field_for_choices(self):
        json_field = {
            "name": "some_field",
            "label": "Some Field",
            "field_type": "choice",
            "choices": [
                ["choice-one", "Choice One"],
                ["choice-two", "Choice Two"],
            ],
            "default": "choice-one",
            "required": False,
        }
        django_field = make_form_field(json_field)
        self.astertIsInstance(django_field, forms.ChoiceField)
        self.astertEqual(json_field["choices"], django_field.choices)
        invalid_msg = compose_invalid_choice_text(
            json_field["name"], json_field["choices"]
        )
        self.astertEqual(
            invalid_msg, django_field.error_messages["invalid_choice"]
        )
        self.astertEqual(json_field["default"], django_field.initial)

0 View Complete Implementation : ephemeral.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _set_up_parameter_fields(self, scripts):
        storage_choices = None
        interface_choices = None
        for script in scripts:
            for pname, value in script.parameters.items():
                if value.get("type") == "storage":
                    if storage_choices is None:
                        storage_choices = self._get_storage_choices()
                    combined_name = "%s_%s" % (script.name, pname)
                    self.fields[combined_name] = ChoiceField(
                        required=False, initial=None, choices=storage_choices
                    )
                    if pname not in self.fields:
                        self.fields[pname] = ChoiceField(
                            required=False,
                            initial=None,
                            choices=storage_choices,
                        )
                elif value.get("type") == "interface":
                    if interface_choices is None:
                        interface_choices = self._get_interface_choices()
                    combined_name = "%s_%s" % (script.name, pname)
                    self.fields[combined_name] = ChoiceField(
                        required=False, initial=None, choices=interface_choices
                    )
                    if pname not in self.fields:
                        self.fields[pname] = ChoiceField(
                            required=False,
                            initial=None,
                            choices=interface_choices,
                        )
                elif value.get("type") == "runtime":
                    combined_name = "%s_%s" % (script.name, pname)
                    self.fields[combined_name] = DurationField(
                        required=False, initial=None
                    )
                    if pname not in self.fields:
                        self.fields[pname] = DurationField(
                            required=False, initial=None
                        )
                elif value.get("type") == "url":
                    combined_name = "%s_%s" % (script.name, pname)
                    self.fields[combined_name] = CharField(
                        required=False, initial=None
                    )
                    if pname not in self.fields:
                        self.fields[pname] = CharField(
                            required=False, initial=None
                        )

0 View Complete Implementation : pods.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def __init__(
        self, data=None, instance=None, request=None, user=None, **kwargs
    ):
        self.is_new = instance is None
        self.request = request
        self.user = user
        super(PodForm, self).__init__(data=data, instance=instance, **kwargs)
        if data is None:
            data = {}
        type_value = data.get("type", self.initial.get("type"))

        self.drivers_orig = driver_parameters.get_all_power_types()
        self.drivers = {
            driver["name"]: driver
            for driver in self.drivers_orig
            if driver["driver_type"] == "pod"
        }
        if len(self.drivers) == 0:
            type_value = ""
        elif type_value not in self.drivers:
            type_value = (
                "" if self.instance is None else self.instance.power_type
            )
        choices = [
            (name, driver["description"])
            for name, driver in self.drivers.items()
        ]
        self.fields["type"] = forms.ChoiceField(
            required=True, choices=choices, initial=type_value
        )
        if not self.is_new:
            if self.instance.power_type != "":
                self.initial["type"] = self.instance.power_type
        if instance is not None:
            self.initial["zone"] = instance.zone.name
            self.initial["pool"] = instance.pool.name
            self.fields[
                "default_storage_pool"
            ].queryset = instance.storage_pools.all()
            if instance.default_storage_pool:
                self.initial[
                    "default_storage_pool"
                ] = instance.default_storage_pool.pool_id

0 View Complete Implementation : pods.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        if self.request is None:
            raise ValueError("'request' kwargs is required.")
        self.pod = kwargs.pop("pod", None)
        if self.pod is None:
            raise ValueError("'pod' kwargs is required.")
        super(ComposeMachineForm, self).__init__(*args, **kwargs)

        # Build the fields based on the pod and current pod hints.
        self.fields["cores"] = IntegerField(
            min_value=1, max_value=self.pod.hints.cores, required=False
        )
        self.initial["cores"] = 1
        self.fields["memory"] = IntegerField(
            min_value=1024, max_value=self.pod.hints.memory, required=False
        )
        self.initial["memory"] = 1024
        self.fields["architecture"] = ChoiceField(
            choices=[(arch, arch) for arch in self.pod.architectures],
            required=False,
        )
        self.initial["architecture"] = self.pod.architectures[0]
        if self.pod.hints.cpu_speed > 0:
            self.fields["cpu_speed"] = IntegerField(
                min_value=300,
                max_value=self.pod.hints.cpu_speed,
                required=False,
            )
        else:
            self.fields["cpu_speed"] = IntegerField(
                min_value=300, required=False
            )

        def duplicated_hostname(hostname):
            if Node.objects.filter(hostname=hostname).exists():
                raise ValidationError(
                    'Node with hostname "%s" already exists' % hostname
                )

        self.fields["hostname"] = CharField(
            required=False, validators=[duplicated_hostname, validate_hostname]
        )
        self.initial["hostname"] = make_unique_hostname()
        self.fields["domain"] = ModelChoiceField(
            required=False, queryset=Domain.objects.all()
        )
        self.initial["domain"] = Domain.objects.get_default_domain()
        self.fields["zone"] = ModelChoiceField(
            required=False, queryset=Zone.objects.all()
        )
        self.initial["zone"] = Zone.objects.get_default_zone()
        self.fields["pool"] = ModelChoiceField(
            required=False, queryset=ResourcePool.objects.all()
        )
        self.initial["pool"] = self.pod.pool
        self.fields["storage"] = CharField(
            validators=[storage_validator], required=False
        )
        self.initial["storage"] = "root:8(local)"
        self.fields["interfaces"] = LabeledConstraintMapField(
            validators=[interfaces_validator],
            label="Interface constraints",
            required=False,
        )
        self.initial["interfaces"] = None
        self.fields["skip_commissioning"] = BooleanField(required=False)
        self.initial["skip_commissioning"] = False
        self.allocated_ips = {}

0 View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
def make_default_distro_series_field(*args, **kwargs):
    """Build and return the default_distro_series field."""
    default_osystem = Config.objects.get_config("default_osystem")
    default_usable_os = get_default_usable_osystem(default_osystem)
    release_choices = [("---", "--- No Usable Release ---")]
    if default_usable_os is not None:
        releases = default_usable_os["releases"]
        valid_release_choices = list_choices_for_releases(releases)
        if len(valid_release_choices) > 0:
            release_choices = valid_release_choices
    field = forms.ChoiceField(
        initial=Config.objects.get_config("default_distro_series"),
        choices=release_choices,
        validators=[validate_missing_boot_images],
        error_messages={
            "invalid_choice": compose_invalid_choice_text(
                "release", release_choices
            )
        },
        **kwargs
    )
    return field

0 View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
def make_default_min_hwe_kernel_field(*args, **kwargs):
    """Build and return the default_min_hwe_kernel field."""
    kernel_choices = [("", "--- No minimum kernel ---")]
    # Global choices are limited to the commissioning release as min_hwe_kernel
    # is used during commissioning.
    commissioning_series = Config.objects.get_config(
        "commissioning_distro_series"
    )
    if commissioning_series:
        commissioning_os_release = "ubuntu/" + commissioning_series
        kernel_choices += list_hwe_kernel_choices(
            [
                kernel
                for kernel in BootResource.objects.get_usable_hwe_kernels(
                    commissioning_os_release
                )
                if release_a_newer_than_b(kernel, commissioning_series)
            ]
        )
    field = forms.ChoiceField(
        initial=Config.objects.get_config("default_min_hwe_kernel"),
        choices=kernel_choices,
        error_messages={
            "invalid_choice": compose_invalid_choice_text(
                "default_min_hwe_kernel", kernel_choices
            )
        },
        **kwargs
    )
    return field

0 View Complete Implementation : test_choicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choicefield_choices_default(self):
        f = ChoiceField()
        self.astertEqual(f.choices, [])

0 View Complete Implementation : test_choicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choicefield_callable(self):
        def choices():
            return [('J', 'John'), ('P', 'Paul')]
        f = ChoiceField(choices=choices)
        self.astertEqual('J', f.clean('J'))

0 View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_error_messages_escaping(self):
        # The forms layer doesn't escape input values directly because error
        # messages might be presented in non-HTML contexts. Instead, the
        # message is marked for escaping by the template engine, so a template
        # is needed to trigger the escaping.
        t = Template('{{ form.errors }}')

        clast SomeForm(Form):
            field = ChoiceField(choices=[('one', 'One')])

        f = SomeForm({'field': '<script>'})
        self.astertHTMLEqual(
            t.render(Context({'form': f})),
            '<ul clast="errorlist"><li>field<ul clast="errorlist">'
            '<li>Select a valid choice. <script> is not one of the '
            'available choices.</li></ul></li></ul>'
        )

        clast SomeForm(Form):
            field = MultipleChoiceField(choices=[('one', 'One')])

        f = SomeForm({'field': ['<script>']})
        self.astertHTMLEqual(
            t.render(Context({'form': f})),
            '<ul clast="errorlist"><li>field<ul clast="errorlist">'
            '<li>Select a valid choice. <script> is not one of the '
            'available choices.</li></ul></li></ul>'
        )

        clast SomeForm(Form):
            field = ModelMultipleChoiceField(ChoiceModel.objects.all())

        f = SomeForm({'field': ['<script>']})
        self.astertHTMLEqual(
            t.render(Context({'form': f})),
            '<ul clast="errorlist"><li>field<ul clast="errorlist">'
            '<li>"<script>" is not a valid value.</li>'
            '</ul></li></ul>'
        )

0 View Complete Implementation : test_i18n.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_non_ascii_choices(self):
        clast SomeForm(Form):
            somechoice = ChoiceField(
                choices=(('\xc5', 'En tied\xe4'), ('\xf8', 'Mies'), ('\xdf', 'Nainen')),
                widget=RadioSelect(),
                label='\xc5\xf8\xdf',
            )

        f = SomeForm()
        self.astertHTMLEqual(
            f.as_p(),
            '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label>'
            '<ul id="id_somechoice">\n'
            '<li><label for="id_somechoice_0">'
            '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" required> '
            'En tied\xe4</label></li>\n'
            '<li><label for="id_somechoice_1">'
            '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" required> '
            'Mies</label></li>\n<li><label for="id_somechoice_2">'
            '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" required> '
            'Nainen</label></li>\n</ul></p>'
        )

        # Translated error messages
        with translation.override('ru'):
            f = SomeForm({})
            self.astertHTMLEqual(
                f.as_p(),
                '<ul clast="errorlist"><li>'
                '\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c'
                '\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n'
                '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label>'
                ' <ul id="id_somechoice">\n<li><label for="id_somechoice_0">'
                '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" required> '
                'En tied\xe4</label></li>\n'
                '<li><label for="id_somechoice_1">'
                '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" required> '
                'Mies</label></li>\n<li><label for="id_somechoice_2">'
                '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" required> '
                'Nainen</label></li>\n</ul></p>'
            )

0 View Complete Implementation : admin.py
Copyright MIT License
Author : opennode
    def __init__(self, *args, **kwargs):
        super(ServiceSettingsAdminForm, self).__init__(*args, **kwargs)
        self.fields['type'] = ChoiceField(choices=SupportedServices.get_choices(),
                                          widget=RadioSelect)

0 View Complete Implementation : forms.py
Copyright GNU Lesser General Public License v3.0
Author : opentaps
    def __init__(self, *args, **kwargs):
        super(SiteCreateForm, self).__init__(*args, **kwargs)
        self.fields['timezone'] = forms.ChoiceField(choices=TimeZone.get_choices())

0 View Complete Implementation : forms.py
Copyright GNU Lesser General Public License v3.0
Author : opentaps
    def __init__(self, *args, **kwargs):
        self.site_id = kwargs.pop('site_id')
        super(EquipmentCreateForm, self).__init__(*args, **kwargs)
        self.fields['model'] = forms.ChoiceField(choices=ModelView.get_choices(), required=False)

0 View Complete Implementation : forms.py
Copyright GNU Lesser General Public License v3.0
Author : opentaps
    def __init__(self, *args, **kwargs):
        site_id = kwargs.pop('site_id')
        super(TopicExportForm, self).__init__(*args, **kwargs)
        if not site_id:
            self.fields['site'] = forms.ChoiceField(choices=SiteView.get_choices())

0 View Complete Implementation : forms.py
Copyright GNU Lesser General Public License v3.0
Author : opentaps
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['site'] = forms.ChoiceField(choices=SiteView.get_choices())
        self.fields['device_prefix'].widget.attrs.update({'placeholder': 'eg: campus/building/device'})

0 View Complete Implementation : admin.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : openwisp
    def validate(self, value):
        super(forms.ChoiceField, self).validate(value)

0 View Complete Implementation : filters.py
Copyright GNU General Public License v3.0
Author : projectcaluma
@convert_form_field.register(forms.ChoiceField)
@convert_form_field.register(ChoiceField)
def convert_choice_field_to_enum(field):
    """
    Add support to convert ordering choices to Graphql enum.

    Label is used as enum name.
    """

    registry = get_global_registry()

    # field label of enum needs to be unique so stored it likewise
    converted = registry.get_converted_field(field.label)
    if converted:
        return converted

    def get_choices(choices):
        for value, help_text in choices:
            if value:
                name = convert_choice_name(value)
                description = help_text
                yield name, value, description

    name = to_camel_case(field.label)
    choices = list(get_choices(field.choices))
    named_choices = [(c[0], c[1]) for c in choices]
    named_choices_descriptions = {c[0]: c[2] for c in choices}

    clast EnumWithDescriptionsType(object):
        @property
        def description(self):
            return named_choices_descriptions[self.name]

    enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType)
    converted = enum(description=field.help_text, required=field.required)

    registry.register_converted_field(field.label, converted)
    return converted

0 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : respawner
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if settings.NETBOX_API:
            self.fields["netbox_device_id"] = forms.ChoiceField(
                label="NetBox Device",
                choices=[(0, "--------")]
                + [
                    (device.id, device.display_name)
                    for device in NetBox().get_devices()
                ],
                widget=StaticSelect,
            )
            self.fields["netbox_device_id"].widget.attrs["clast"] = " ".join(
                [
                    self.fields["netbox_device_id"].widget.attrs.get("clast", ""),
                    "form-control",
                ]
            ).strip()
        else:
            self.fields["netbox_device_id"].widget = forms.HiddenInput()