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 : test_choicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choicefield_4(self):
        f = ChoiceField(
            choices=[
                ('Numbers', (('1', 'One'), ('2', 'Two'))),
                ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other'),
            ]
        )
        self.astertEqual('1', f.clean(1))
        self.astertEqual('1', f.clean('1'))
        self.astertEqual('3', f.clean(3))
        self.astertEqual('3', f.clean('3'))
        self.astertEqual('5', f.clean(5))
        self.astertEqual('5', f.clean('5'))
        msg = "'Select a valid choice. 6 is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean('6')

3 View Complete Implementation : forms.py
Copyright MIT License
Author : rkhleics
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if settings.FLAT_MENUS_HANDLE_CHOICES:
            self.fields['handle'] = forms.ChoiceField(
                label=self.fields['handle'].label,
                choices=settings.FLAT_MENUS_HANDLE_CHOICES
            )

3 View Complete Implementation : test_fields.py
Copyright MIT License
Author : labd
    def test_radio_field(self):
        data = self.get_form_field_data('radio')
        cls = wsf_fields.RadioField()
        field = cls.get_formfield(data)

        self.astertIsInstance(field, forms.ChoiceField)
        self.astertIsInstance(field.widget, forms.widgets.RadioSelect)
        self.astertEqual(field.label, data['label'])
        self.astertEqual(field.required, data['required'])
        self.astertEqual(field.help_text, data['help_text'])
        self.astertEqual(field.choices, [(c, c) for c in data['choices']])

3 View Complete Implementation : storage_layouts.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def setup_field(self, required=False):
        choices = get_storage_layout_choices()
        invalid_choice_message = compose_invalid_choice_text(
            "storage_layout", choices
        )
        self.fields["storage_layout"] = forms.ChoiceField(
            choices=choices,
            required=required,
            error_messages={"invalid_choice": invalid_choice_message},
        )

3 View Complete Implementation : interface_link.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def set_up_link_id_field(self):
        link_choices = [(link.id, link.id) for link in self.links]
        invalid_choice = compose_invalid_choice_text("link_id", link_choices)
        self.fields["link_id"] = forms.ChoiceField(
            choices=link_choices,
            required=False,
            error_messages={"invalid_choice": invalid_choice},
        )

3 View Complete Implementation : fields.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def __init__(self, *args, **kwargs):
        errors = self.default_error_messages.copy()
        if 'error_messages' in kwargs:
            errors.update(kwargs['error_messages'])
        
        fields = (
            forms.ChoiceField(choices=self.EXP_MONTH, error_messages={'invalid': errors['invalid_month']}),
            forms.ChoiceField(choices=self.EXP_YEAR, error_messages={'invalid': errors['invalid_year']}),
        )
        
        super(CreditCardExpiryField, self).__init__(fields, *args, **kwargs)
        self.widget = CreditCardExpiryWidget(widgets=[fields[0].widget, fields[1].widget])

3 View Complete Implementation : test_forms.py
Copyright Apache License 2.0
Author : ooknosi
    def test_MaterialForm_materializes_ChoiceField(self):
        """django.forms.widgets.Select should be converted to
        material_widgets.widgets.MaterialSelect.
        """

        clast SelectForm(MaterialForm):
            select = forms.ChoiceField()

        form = SelectForm()
        self.astertEqual(
            type(form.fields['select'].widget),
            widgets.MaterialSelect,
            )

3 View Complete Implementation : forms.py
Copyright MIT License
Author : ayshrv
    def __init__(self, *args, **kwargs):
        self.list_with_index=[]
        self.list1=[]
        list = kwargs.pop('list')
        for i in list:
            self.list1.append(i)
        for index, value in enumerate(self.list1):
            self.list_with_index.append((index,str(value)))
        super(ChoiceResultForm, self).__init__(*args, **kwargs)
        # self.fields['Candidates'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=self.list_with_index,required=False)
        self.fields['ResultID'] = forms.ChoiceField(choices=self.list_with_index,required=True)

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def __init__(self, choices, validators, *args, **kwargs):
        """
        :param validators:  A dict that maps query type
        values to validators.
        """
        if validators is None:
            validators = {}
        super(MulsatypeQueryField, self).__init__(*args, **kwargs)
        self.fields = (
            forms.ChoiceField(choices=choices),
            forms.CharField(min_length=1)
        )
        self.widget = MulsatypeQueryWidget(
            (forms.Select(choices=choices),
             forms.TextInput())
        )
        self.query_validators = validators

3 View Complete Implementation : dashboard.py
Copyright Apache License 2.0
Author : BeanWei
    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'widget_type':
            widgets = widget_manager.get_widgets(self.request.GET.get('page_id', ''))
            form_widget = WidgetTypeSelect(widgets)
            return forms.ChoiceField(choices=[(w.widget_type, w.description) for w in widgets],
                                     widget=form_widget, label=_('Widget Type'))
        if 'page_id' in self.request.GET and db_field.name == 'page_id':
            kwargs['widget'] = forms.HiddenInput
        field = super(
            UserWidgetAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        return field

3 View Complete Implementation : storage_layouts.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def setup_root_device_field(self):
        """Setup the possible root devices."""
        choices = [
            (block_device.id, block_device.id)
            for block_device in self.block_devices
        ]
        invalid_choice_message = compose_invalid_choice_text(
            "root_device", choices
        )
        self.fields["root_device"] = forms.ChoiceField(
            choices=choices,
            required=False,
            error_messages={"invalid_choice": invalid_choice_message},
        )

3 View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
def make_commissioning_distro_series_field(*args, **kwargs):
    """Build and return the commissioning_distro_series field."""
    usable_oses = list_all_usable_osystems()
    commissioning_choices = list_commissioning_choices(usable_oses)
    if len(commissioning_choices) == 0:
        commissioning_choices = [("---", "--- No Usable Release ---")]
    field = forms.ChoiceField(
        initial=Config.objects.get_config("commissioning_distro_series"),
        choices=commissioning_choices,
        validators=[validate_missing_boot_images],
        error_messages={
            "invalid_choice": compose_invalid_choice_text(
                "commissioning_distro_series", commissioning_choices
            )
        },
        **kwargs
    )
    return field

3 View Complete Implementation : forms.py
Copyright MIT License
Author : cyanfish
    def __init__(self, *args, **kwargs):
        current_league = kwargs.pop('current_league')
        leagues = kwargs.pop('leagues')
        boards = kwargs.pop('boards')
        teams = kwargs.pop('teams')
        super(TvFilterForm, self).__init__(*args, **kwargs)

        self.fields['league'] = forms.ChoiceField(
            choices=[('all', 'All Leagues')] + [(l.tag, l.name) for l in leagues],
            initial=current_league.tag)
        if boards is not None and len(boards) > 0:
            self.fields['board'] = forms.ChoiceField(
                choices=[('all', 'All Boards')] + [(n, 'Board %d' % n) for n in boards])
        if teams is not None and len(teams) > 0:
            self.fields['team'] = forms.ChoiceField(
                choices=[('all', 'All Teams')] + [(team.number, team.name) for team in teams])

3 View Complete Implementation : test_choicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choicefield_2(self):
        f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
        self.astertEqual('', f.clean(''))
        self.astertEqual('', f.clean(None))
        self.astertEqual('1', f.clean(1))
        self.astertEqual('1', f.clean('1'))
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean('3')

3 View Complete Implementation : formfields.py
Copyright MIT License
Author : Arx-Game
    def webform_field(self, caller=None):
        options = {'label': self.full_name}
        if self.required is not None:
            options['required'] = self.required

        choices = []
        if not self.required:
            choices.append((-1, '----'))

        if caller and caller.pracsationer:
            attunements = {}
            for attunement in Attunement.objects.filter(pracsationer=caller.pracsationer).all():
                attunements[attunement.obj.name] = attunement.obj.id
            for key in sorted(attunements.keys()):
                choices.append((attunements[key], key))

        options['choices'] = choices
        return django.forms.ChoiceField(**options)

3 View Complete Implementation : test_choicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choicefield_disabled(self):
        f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')], disabled=True)
        self.astertWidgetRendersTo(
            f,
            '<select id="id_f" name="f" disabled><option value="J">John</option>'
            '<option value="P">Paul</option></select>'
        )

3 View Complete Implementation : forms.py
Copyright MIT License
Author : F0RE1GNERS
  def __init__(self, *args, **kwargs):
    langs = dict(LANG_CHOICE)
    contest_problem_list = kwargs.pop('contest_problem_list')
    contest_allowed_lang = kwargs.pop('contest_allowed_lang')
    super(ContestSubmitForm, self).__init__(*args, **kwargs)
    self.fields['problem_identifier'] = forms.ChoiceField(
      choices=[(contest_problem.identifier, "{}. {}".format(contest_problem.identifier, contest_problem.problem.satle))
               for contest_problem in contest_problem_list])
    self.fields['lang'] = forms.ChoiceField(
      choices=((x, langs[x]) for x in contest_allowed_lang)
    )

3 View Complete Implementation : test_wiki_templatetags.py
Copyright MIT License
Author : python-discord
    def test_get_field_options(self):
        unbound_field = ChoiceField()
        field = BoundField(Form(), unbound_field, "field")

        context = Context({"field": field})
        self.TEMPLATE.render(context)

3 View Complete Implementation : formfields.py
Copyright MIT License
Author : Arx-Game
    def webform_field(self, caller=None):
        options = {'label': self.full_name}
        if self.required is not None:
            options['required'] = self.required

        choices = (
            (-1, '----'),
            (Alignment.PRIMAL.id, "Primal"),
            (Alignment.ELYSIAN.id, "Elysian"),
            (Alignment.ABYSSAL.id, "Abyssal")
        )

        options['choices'] = choices
        return django.forms.ChoiceField(**options)

3 View Complete Implementation : forms_special_fields.py
Copyright MIT License
Author : robotichead
    def clean(self, value):

        value = super(forms.ChoiceField, self).clean(value)
        if value in (None, ''):
            value = u''
        value = forms.util.smart_str(value)
        if value == u'':
            return value
        valid_values = []
        for group_label, group in self.choices:
            valid_values += [str(k) for k, v in group]
        if value not in valid_values:
            raise ValidationError(gettext(u'Select a valid choice. That choice is not one of the available choices.'))
        return value

3 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['clast_name'] = forms.ChoiceField(
            choices=[(clast_name, clast_name) for clast_name in
                     set(TextUnitClastification.objects.values_list('clast_name', flat=True))],
            required=True,
            help_text='Text Unit clast name')

3 View Complete Implementation : interface_link.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def set_up_id_field(self):
        link_ids = self.instance.ip_addresses.all().values_list(
            "id", flat=True
        )
        link_choices = [(link_id, link_id) for link_id in link_ids]
        invalid_choice = compose_invalid_choice_text("id", link_choices)
        self.fields["id"] = forms.ChoiceField(
            choices=link_choices,
            required=True,
            error_messages={"invalid_choice": invalid_choice},
        )

3 View Complete Implementation : formfields.py
Copyright MIT License
Author : Arx-Game
    def webform_field(self, caller=None):
        options = {'label': self.full_name}
        if self.required is not None:
            options['required'] = self.required

        choices = [(-1, "----")]
        for affinity in Affinity.objects.all():
            choices.append((affinity.id, affinity.name))

        options['choices'] = choices
        return django.forms.ChoiceField(**options)

3 View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
def make_default_osystem_field(*args, **kwargs):
    """Build and return the default_osystem field."""
    usable_oses = list_all_usable_osystems()
    os_choices = list_osystem_choices(usable_oses, include_default=False)
    if len(os_choices) == 0:
        os_choices = [("---", "--- No Usable Operating System ---")]
    field = forms.ChoiceField(
        initial=Config.objects.get_config("default_osystem"),
        choices=os_choices,
        validators=[validate_missing_boot_images],
        error_messages={
            "invalid_choice": compose_invalid_choice_text(
                "osystem", os_choices
            )
        },
        **kwargs
    )
    return field

3 View Complete Implementation : documents.py
Copyright Apache License 2.0
Author : byro
    def __init__(self, *args, **kwargs):
        initial_category = kwargs.pop("initial_category", "byro.docameents.misc")

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

        categories = get_docameent_category_names()

        self.fields["category"] = forms.ChoiceField(
            choices=sorted(categories.items()), initial=initial_category
        )
        if "clast" in self.fields["date"].widget.attrs:
            self.fields["date"].widget.attrs["clast"] += " datepicker"
        else:
            self.fields["date"].widget.attrs["clast"] = "datepicker"

3 View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
def make_active_discovery_interval_field(*args, **kwargs):
    """Build and return the network_discovery field."""
    field = forms.ChoiceField(
        initial=CONFIG_ITEMS["active_discovery_interval"]["default"],
        choices=ACTIVE_DISCOVERY_INTERVAL_CHOICES,
        error_messages={
            "invalid_choice": compose_invalid_choice_text(
                "active_discovery_interval", ACTIVE_DISCOVERY_INTERVAL_CHOICES
            )
        },
        **kwargs
    )
    return field

3 View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
def make_dnssec_validation_field(*args, **kwargs):
    """Build and return the dnssec_validation field."""
    field = forms.ChoiceField(
        initial=CONFIG_ITEMS["dnssec_validation"]["default"],
        choices=DNSSEC_VALIDATION_CHOICES,
        error_messages={
            "invalid_choice": compose_invalid_choice_text(
                "dnssec_validation", DNSSEC_VALIDATION_CHOICES
            )
        },
        **kwargs
    )
    return field

3 View Complete Implementation : forms.py
Copyright MIT License
Author : cyanfish
    def __init__(self, *args, **kwargs):
        leagues = kwargs.pop('leagues')
        super(ContactForm, self).__init__(*args, **kwargs)

        self.fields['league'] = forms.ChoiceField(choices=[(l.tag, l.name) for l in leagues])

        if settings.DEBUG:
            del self.fields['captcha']

3 View Complete Implementation : storage_layouts.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def setup_cache_device_field(self):
        """Setup the possible cache devices."""
        if self.boot_disk is None:
            return
        choices = [
            (block_device.id, block_device.id)
            for block_device in self.block_devices
            if block_device != self.boot_disk
        ]
        invalid_choice_message = compose_invalid_choice_text(
            "cache_device", choices
        )
        self.fields["cache_device"] = forms.ChoiceField(
            choices=choices,
            required=False,
            error_messages={"invalid_choice": invalid_choice_message},
        )

3 View Complete Implementation : formfields.py
Copyright MIT License
Author : Arx-Game
    def webform_field(self, caller=None):
        options = {'label': self.full_name}
        if self.required is not None:
            options['required'] = self.required

        choices = []
        if not self.required:
            choices.append((-1, '----'))

        if caller and caller.pracsationer:
            effects = {}
            for effect_record in PracsationerEffect.objects.filter(pracsationer=caller.pracsationer).all():
                effects[effect_record.effect.name] = effect_record.effect.id
            for key in sorted(effects.keys()):
                choices.append((effects[key], key))

        options['choices'] = choices
        return django.forms.ChoiceField(**options)

3 View Complete Implementation : test_choicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choicefield_1(self):
        f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')])
        with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean('')
        with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean(None)
        self.astertEqual('1', f.clean(1))
        self.astertEqual('1', f.clean('1'))
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean('3')

3 View Complete Implementation : forms.py
Copyright MIT License
Author : diegojromerolopez
    def __init__(self, *args, **kwargs):
        super(BuildForecasterForm, self).__init__(*args, **kwargs)

        current_request = CrequestMiddleware.get_request()
        current_user = current_request.user
        boards = get_user_boards(current_user)
        members = Member.get_user_team_members(current_user)
        self.fields["model"] = forms.ChoiceField(label="Regression model")
        self.fields["model"].choices = REGRESSION_MODELS
        self.fields["board"].choices = [("", "All")]+[(board.id, board.name) for board in boards]
        self.fields["member"].choices = [("", "None")] + [(member.id, member.external_username) for member in members]

3 View Complete Implementation : test_choicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choicefield_3(self):
        f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
        self.astertEqual('J', f.clean('J'))
        msg = "'Select a valid choice. John is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean('John')

3 View Complete Implementation : views.py
Copyright MIT License
Author : Arx-Game
    def __init__(self, caller, *args, **kwargs):
        super(ActionForm,self).__init__(caller, *args, **kwargs)

        # Do black magic to prepend the Category field
        keys = self.fields.keys()
        self.fields['category'] = forms.ChoiceField(choices=self.CATEGORY_CHOICES, label='What type of action is this?')
        keys.insert(0, 'category')
        new_fields = (OrderedDict)([k, self.fields[k]] for k in keys)
        self.fields = new_fields

3 View Complete Implementation : test_choicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choicefield_callable_may_evaluate_to_different_values(self):
        choices = []

        def choices_as_callable():
            return choices

        clast ChoiceFieldForm(Form):
            choicefield = ChoiceField(choices=choices_as_callable)

        choices = [('J', 'John')]
        form = ChoiceFieldForm()
        self.astertEqual([('J', 'John')], list(form.fields['choicefield'].choices))

        choices = [('P', 'Paul')]
        form = ChoiceFieldForm()
        self.astertEqual([('P', 'Paul')], list(form.fields['choicefield'].choices))

3 View Complete Implementation : forms.py
Copyright MIT License
Author : F0RE1GNERS
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    filter_children = get_children_tag_id(self.instance.pk)
    self.fields['parent'] = forms.ChoiceField(
      choices=[(-1, 'None')] + [(tag.pk, tag.name) for tag in Tag.objects.exclude(pk__in=filter_children)]
    )
    if hasattr(self.instance, 'taginfo'):
      self.fields['description'].initial = self.instance.taginfo.description
      self.fields['parent'].initial = self.instance.taginfo.parent_id

3 View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choicefield(self):
        e = {
            'required': 'REQUIRED',
            'invalid_choice': '%(value)s IS INVALID CHOICE',
        }
        f = ChoiceField(choices=[('a', 'aye')], error_messages=e)
        self.astertFormErrors(['REQUIRED'], f.clean, '')
        self.astertFormErrors(['b IS INVALID CHOICE'], f.clean, 'b')

3 View Complete Implementation : formfields.py
Copyright MIT License
Author : Arx-Game
    def webform_field(self, caller=None):
        options = {'label': self.full_name}
        if self.required is not None:
            options['required'] = self.required

        choices = []
        if not self.required:
            choices.append((-1, '----'))

        if caller and caller.pracsationer:
            attunements = {}
            for attunement in FamiliarAttunement.objects.filter(pracsationer=caller.pracsationer).all():
                attunements[attunement.familiar.name] = attunement.familiar.id
            for key in sorted(attunements.keys()):
                choices.append((attunements[key], key))

        options['choices'] = choices
        return django.forms.ChoiceField(**options)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : opennode
    def __init__(self, *args, **kwargs):
        super(CustomerAdminForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.owners = self.instance.get_owners()
            self.support_users = self.instance.get_support_users()
            self.fields['owners'].initial = self.owners
            self.fields['support_users'].initial = self.support_users
        else:
            self.owners = User.objects.none()
            self.support_users = User.objects.none()
        self.fields['agreement_number'].initial = models.get_next_agreement_number()

        textarea_attrs = {'cols': '40', 'rows': '4'}
        self.fields['contact_details'].widget.attrs = textarea_attrs
        self.fields['access_subnets'].widget.attrs = textarea_attrs
        type_choices = ['']
        type_choices.extend(settings.WALDUR_CORE['COMPANY_TYPES'])
        self.fields['type'] = ChoiceField(required=False, choices=[(t, t) for t in type_choices])

3 View Complete Implementation : test_fields.py
Copyright MIT License
Author : labd
    def test_dropdown_field(self):
        data = self.get_form_field_data('dropdown')
        cls = wsf_fields.DropdownField()
        field = cls.get_formfield(data)

        self.astertIsInstance(field, forms.ChoiceField)
        self.astertIsInstance(field.widget, forms.widgets.Select)
        self.astertEqual(field.label, data['label'])
        self.astertEqual(field.required, data['required'])
        self.astertEqual(field.help_text, data['help_text'])
        self.astertEqual(field.choices, [(c, c) for c in data['choices']])

        data['empty_label'] = 'Please Select'
        field = cls.get_formfield(data)
        self.astertEqual(field.choices[0], ('', 'Please Select'))

3 View Complete Implementation : test_wiki_templatetags.py
Copyright MIT License
Author : python-discord
    def test_get_field_options_value(self):
        unbound_field = ChoiceField()
        field = BoundField(Form(initial={"field": "Value"}), unbound_field, "field")

        context = Context({"field": field})
        self.TEMPLATE.render(context)

3 View Complete Implementation : fields.py
Copyright MIT License
Author : Arx-Game
    def webform_field(self, caller=None):
        options = {'label': self.full_name}
        if self.required is not None:
            options['required'] = self.required
        options['choices'] = self._choices
        return django.forms.ChoiceField(**options)

3 View Complete Implementation : forms_special_fields.py
Copyright MIT License
Author : robotichead
    def clean(self, value):
        value = super(forms.ChoiceField, self).clean(value)
        if value in (None, ''):
            value = u''
        value = forms.util.smart_str(value)
        if value == u'':
            return value
        valid_values = []
        for group_label, group in self.choices:
            valid_values += [str(k) for k, v in group]
        if value not in valid_values:
            raise ValidationError(gettext(u'Select a valid choice. That choice is not one of the available choices.'))
        return value

3 View Complete Implementation : forms.py
Copyright GNU Lesser General Public License v3.0
Author : lgoodridge
    def __init__(self, user, *args, **kwargs):
        """
        Set the choices to the current profile's verified linked emails.
        """
        super(ChangePrimaryEmailForm, self).__init__(*args, **kwargs)
        self.user = user
        verified_emails = LinkedEmail.objects.filter(
                profile=self.user.uniauth_profile, is_verified=True).all()
        choices = map(lambda x: (x.address, x.address), verified_emails)
        self.fields['email'] = forms.ChoiceField(choices=choices)
        self.fields['email'].initial = self.user.email

3 View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : BeanWei
    def __init__(self, field, lookup_choices, *args, **kwargs):
        fields = (
            field,
            forms.ChoiceField(choices=lookup_choices)
        )
        defaults = {
            'widgets': [f.widget for f in fields],
        }
        widget = LookupTypeWidget(**defaults)
        kwargs['widget'] = widget
        kwargs['help_text'] = field.help_text
        super(LookupTypeField, self).__init__(fields, *args, **kwargs)

3 View Complete Implementation : select.py
Copyright MIT License
Author : abelardopardo
    def __init__(self, *args, **kargs):
        """Adjust the choices for the select fields."""
        given_how = kargs.pop('how_merge', None)
        self.how_merge_initial = next((
            mrg for mrg in self.how_merge_choices if given_how == mrg[0]),
            None)

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

        self.fields['how_merge'] = forms.ChoiceField(
            initial=self.how_merge_initial,
            choices=self.how_merge_choices,
            required=True,
            label=_('Method to select rows to merge'),
            help_text=self.merge_help)

3 View Complete Implementation : views.py
Copyright MIT License
Author : Arx-Game
    def __init__(self, caller, *args, **kwargs):
        super(astistForm,self).__init__(*args, **kwargs)
        skills = []
        for k, v in caller.db.skills.iteritems():
            skills.append((k, k.capitalize()))
        self.fields['skill_choice'] = forms.ChoiceField(choices=skills, label='Skill to Roll')

3 View Complete Implementation : formfields.py
Copyright MIT License
Author : Arx-Game
    def webform_field(self, caller=None):
        options = {'label': self.full_name}
        if self.required is not None:
            options['required'] = self.required

        choices = []
        if not self.required:
            choices.append((-1, '----'))

        if caller and caller.pracsationer:
            spells = {}
            for spell_record in PracsationerSpell.objects.filter(pracsationer=caller.pracsationer).all():
                spells[spell_record.spell.name] = spell_record.spell.id
            for key in sorted(spells.keys()):
                choices.append((spells[key], key))

        options['choices'] = choices
        return django.forms.ChoiceField(**options)

3 View Complete Implementation : forms.py
Copyright MIT License
Author : cyanfish
    def __init__(self, *args, **kwargs):
        reg = kwargs.pop('registration')
        super(ApproveRegistrationForm, self).__init__(*args, **kwargs)

        workflow = ApproveRegistrationWorkflow(reg)

        self.fields['send_confirm_email'].initial = workflow.default_send_confirm_email
        self.fields['invite_to_slack'].initial = workflow.default_invite_to_slack

        section_list = reg.season.section_list()
        if len(section_list) > 1:
            section_options = [(season.id, season.section.name) for season in section_list]
            self.fields['section'] = forms.ChoiceField(choices=section_options,
                                                       initial=workflow.default_section.id)

        if workflow.is_late:
            self.fields['retroactive_byes'] = forms.IntegerField(initial=workflow.default_byes)
            self.fields['late_join_points'] = forms.FloatField(initial=workflow.default_ljp)

3 View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
def make_network_discovery_field(*args, **kwargs):
    """Build and return the network_discovery field."""
    field = forms.ChoiceField(
        initial=CONFIG_ITEMS["network_discovery"]["default"],
        choices=NETWORK_DISCOVERY_CHOICES,
        error_messages={
            "invalid_choice": compose_invalid_choice_text(
                "network_discovery", NETWORK_DISCOVERY_CHOICES
            )
        },
        **kwargs
    )
    return field