Python django.forms.ChoiceField() Examples

The following are 30 code examples for showing how to use django.forms.ChoiceField(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: notes.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(NoteForm, self).__init__(*args, **kwargs)
        note = kwargs['instance']
        self.fields['sender'] = forms.ChoiceField(
            label=_('From'),
            choices=note.get_sender_choices(),
            widget=forms.Select(attrs={'class': 'span12'})
        )

        self.fields['body'].widget = AutocompleteTextarea(
            rows=20,
            choices=Template.templates()
        )

        if note.order:
            url = reverse('notes-render_template', args=[note.order.pk])
            self.fields['body'].widget.attrs['data-url'] = url 
Example 2
Project: coursys   Author: sfu-fas   File: select.py    License: GNU General Public License v3.0 6 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        the_choices = self.get_choices()

        c = forms.ChoiceField(required=self.config['required'],
            label=self.config['label'],
            help_text=self.config['help_text'],
            choices=the_choices)

        if fieldsubmission:
            initial=fieldsubmission.data['info']
            c.initial=initial

        if not self.config['required']:
            c.choices.insert(0, ('', '\u2014'))

        return c 
Example 3
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_config(self, name, default=None):
        raw_value = self.event.config.get(name)
        field = self.CONFIG_FIELDS[name]

        try:
            if raw_value is None:
                if field.initial is not None and field.initial != '':
                    return field.to_python(field.initial)
                else:
                    return default
            else:
                return field.to_python(raw_value)
        except forms.ValidationError:
            # XXX: A hack to get around ChoiceField stuff. The idea is that if the value is in
            #      the config field, then it was most likely valid when the event was created.
            return raw_value 
Example 4
Project: heltour   Author: cyanfish   File: forms.py    License: MIT License 6 votes vote down vote up
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]) 
Example 5
Project: peering-manager   Author: respawner   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
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["class"] = " ".join(
                [
                    self.fields["netbox_device_id"].widget.attrs.get("class", ""),
                    "form-control",
                ]
            ).strip()
        else:
            self.fields["netbox_device_id"].widget = forms.HiddenInput() 
Example 6
Project: anytask   Author: znick   File: forms.py    License: MIT License 6 votes vote down vote up
def __init__(self, course, *args, **kwargs):
        forms.Form.__init__(self, *args, **kwargs)

        self.groups = {}
        self.teachers = get_teacher_choises(course)
        groups_teacher = {}
        for default_teacher in DefaultTeacher.objects.filter(group__in=course.groups.all()):
            groups_teacher[default_teacher.group.id] = default_teacher.teacher.id

        for group in course.groups.all():
            group_key = "group_{0}".format(group.id)
            self.groups[group_key] = group
            self.fields[group_key] = forms.ChoiceField(
                initial=groups_teacher.get(group.id, 0),
                choices=self.teachers,
                label=group.name
            ) 
Example 7
Project: django-seo   Author: whyflyru   File: admin.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_view_form(metadata_class):
    model_class = metadata_class._meta.get_model('view')

    # Restrict content type choices to the models set in seo_models
    view_choices = [(key, " ".join(key.split("_"))) for key in get_seo_views(metadata_class)]
    view_choices.insert(0, ("", "---------"))

    # Get a list of fields, with _view at the start
    important_fields = ['_view'] + core_choice_fields(metadata_class)
    _fields = important_fields + list(fields_for_model(model_class,
                                                  exclude=important_fields).keys())

    class ModelMetadataForm(forms.ModelForm):
        _view = forms.ChoiceField(label=capfirst(_("view")),
                                  choices=view_choices, required=False)

        class Meta:
            model = model_class
            fields = _fields

    return ModelMetadataForm 
Example 8
Project: starthinker   Author: google   File: forms_json.py    License: Apache License 2.0 6 votes vote down vote up
def get_field_kind(field):
  if field['kind'] == 'string':
    return forms.CharField(max_length=255, required=False)
  elif field['kind'] == 'email':
    return forms.EmailField(max_length=255, required=False)
  elif field['kind'] == 'integer':
    return forms.IntegerField(required=False)
  elif field['kind'] == 'boolean':
    return forms.BooleanField(required=False)
  elif field['kind'] == 'text':
    return forms.CharField(widget=forms.Textarea(), required=False)
  elif field['kind'] == 'choice':
    return forms.ChoiceField(choices=map(lambda c: (c,c), field['choices']))
  elif field['kind'] == 'timezones':
    return TimezoneField()
  elif field['kind'] == 'authentication':
    return SwitchField('user', 'service', required=True)
  elif field['kind'] == 'json':
    return JsonField(required=False)
  elif field['kind'] == 'integer_list':
    return CommaSeparatedIntegerField(required=False)
  elif field['kind'] == 'string_list':
    return CommaSeparatedCharField(required=False)
  else:
    return forms.CharField(max_length=255, required=False) 
Example 9
Project: byro   Author: byro   File: registration.py    License: Apache License 2.0 6 votes vote down vote up
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")) 
Example 10
Project: boss   Author: jhuapl-boss   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 11
Project: yournextrepresentative   Author: mysociety   File: forms.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        from .election_specific import shorten_post_label
        election = kwargs.pop('election')
        super(AddCandidacyPickPostForm, self).__init__(*args, **kwargs)
        self.fields['post'] = forms.ChoiceField(
            label=_('Post in %s') % election.name,
            choices=[('', '')] + sorted(
                [
                    (post.extra.slug,
                     shorten_post_label(post.label))
                    for post in Post.objects.select_related('extra').filter(extra__elections=election)
                ],
                key=lambda t: t[1]
            ),
            widget=forms.Select(attrs={'class': 'post-select'}),
        ) 
Example 12
Project: Servo   Author: fpsw   File: base.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ChoiceField, self).__init__(*args, **kwargs)
        self.widget.attrs['class'] = 'span12' 
Example 13
Project: Servo   Author: fpsw   File: repairs.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        from servo.lib.utils import empty
        super(GsxRepairForm, self).__init__(*args, **kwargs)
        repair = self.instance
        techs = User.techies.filter(location=repair.order.location)
        c = [(u.tech_id, u.get_full_name()) for u in techs]
        c.insert(0, ('', '-------------------',))
        self.fields['tech_id'] = forms.ChoiceField(choices=c,
                                                   required=False,
                                                   label=_('Technician'))
        self.fields['parts'].initial = repair.order.get_parts()

        if repair.can_mark_complete is False:
            del(self.fields['mark_complete'])
            del(self.fields['replacement_sn'])

        choices = Template.templates()
        for f in ('notes', 'symptom', 'diagnosis',):
            self.fields[f].widget = AutocompleteTextarea(choices=choices)

        symptom_codes = self.instance.get_symptom_code_choices()
        self.fields['symptom_code'] = forms.ChoiceField(choices=symptom_codes,
                                                        label=_('Symptom group'))

        if empty(self.instance.symptom_code):
            # default to the first choice
            self.instance.symptom_code = symptom_codes[0][0]

        issue_codes = self.instance.get_issue_code_choices()
        self.fields['issue_code'] = forms.ChoiceField(choices=issue_codes,
                                                      label=_('Issue code')) 
Example 14
Project: Servo   Author: fpsw   File: orders.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(OrderItemForm, self).__init__(*args, **kwargs)

        if self.instance:
            product = self.instance.product
            if product.can_order_from_gsx():
                CODES = symptom_codes(product.component_code)
                self.fields['comptia_code'] = forms.ChoiceField(choices=CODES,
                                                                label=_('Symptom code'))
                self.fields['comptia_modifier'] = forms.ChoiceField(
                    choices=gsxws.MODIFIERS,
                    initial="B",
                    label=_('Symptom modifier')
                ) 
Example 15
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, event=None, *args, **kwargs):
        super(DonationEntryForm, self).__init__(*args, **kwargs)
        minDonationAmount = (
            event.minimumdonation if event is not None else Decimal('1.00')
        )
        self.fields['amount'] = forms.DecimalField(
            decimal_places=2,
            min_value=minDonationAmount,
            max_value=Decimal('100000'),
            label='Donation Amount (min ${0})'.format(minDonationAmount),
            widget=tracker.widgets.NumberInput(
                attrs={
                    'id': 'iDonationAmount',
                    'min': str(minDonationAmount),
                    'step': '0.01',
                }
            ),
            required=True,
        )
        self.fields['comment'] = forms.CharField(widget=forms.Textarea, required=False)
        self.fields['requestedvisibility'] = forms.ChoiceField(
            initial='CURR',
            choices=models.Donation._meta.get_field('requestedvisibility').choices,
            label='Name Visibility',
        )
        self.fields['requestedalias'] = forms.CharField(
            max_length=32, label='Preferred Alias', required=False
        )
        self.fields['requestedemail'] = forms.EmailField(
            max_length=128, label='Preferred Email', required=False
        )
        self.fields['requestedsolicitemail'] = forms.ChoiceField(
            initial='CURR',
            choices=models.Donation._meta.get_field('requestedsolicitemail').choices,
            label='Charity Email Opt In',
        ) 
Example 16
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, model, objects, *args, **kwargs):
        super(MergeObjectsForm, self).__init__(*args, **kwargs)
        self.model = model
        self.choices = []
        for objId in objects:
            choice_name = '#%d: ' % objId + str(self.model.objects.get(id=objId))
            self.choices.append((objId, choice_name))
        self.fields['root'] = forms.ChoiceField(choices=self.choices, required=True)
        self.fields['objects'] = forms.CharField(
            initial=','.join([str(i) for i in objects]), widget=forms.HiddenInput()
        ) 
Example 17
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(PrizeAcceptanceForm, self).__init__(*args, **kwargs)
        self.accepted = None

        if 'data' in kwargs and kwargs['data'] is not None:
            if 'accept' in kwargs['data']:
                self.accepted = True
            elif 'deny' in kwargs['data']:
                self.accepted = False

        self.fields['count'] = forms.ChoiceField(
            initial=self.instance.pendingcount,
            choices=list([(x, x) for x in range(1, self.instance.pendingcount + 1)]),
            label='Count',
            help_text='You were selected to win more than one copy of this prize, please select how many you would like to take, or press Deny All if you do not want any of them.',
        )
        if self.instance.pendingcount == 1:
            self.fields['count'].widget = forms.HiddenInput()
        self.fields['total'] = forms.IntegerField(
            initial=self.instance.pendingcount,
            validators=[positive],
            widget=forms.HiddenInput(),
        )
        self.fields['comments'] = forms.CharField(
            max_length=512,
            label='Notes',
            required=False,
            help_text='Please put any additional notes here (such as if you have the option of customizing your prize before it is shipped, or additional delivery information).',
            widget=forms.Textarea(attrs=dict(cols=40, rows=2)),
        ) 
Example 18
Project: coursys   Author: sfu-fas   File: mc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_entry_field(self, questionanswer=None, student=None):
        options = self.version.config.get('options', [])
        permute = self.version.config.get('permute', 'keep')
        show_no_answer = self.version.config.get('show_no_answer', 'noshow')
        if questionanswer:
            initial = questionanswer.answer.get('data', MultipleChoice.NA)
        else:
            initial = MultipleChoice.NA

        options = list(enumerate(options))  # keep original positions so the input values match that, but students see a possibly-randomized order

        if student and permute == 'permute':
            rand = self.question.quiz.random_generator(str(student.id) + '-' + str(self.question.id) + '-' + str(self.version.id))
            options = rand.permute(options)
        elif student and permute == 'not-last':
            rand = self.question.quiz.random_generator(str(student.id) + '-' + str(self.question.id) + '-' + str(self.version.id))
            last = options[-1]
            options = rand.permute(options[:-1])
            options.append(last)

        choices = [
            (OPTION_LETTERS[opos], mark_safe('<span class="mc-letter">' + OPTION_LETTERS[i] + '.</span> ') + escape(o[0]))
            for i, (opos, o)
            in enumerate(options)
        ]

        if show_no_answer == 'show':
            choices.append((MultipleChoice.NA, 'no answer'))

        field = forms.ChoiceField(required=False, initial=initial, choices=choices, widget=forms.RadioSelect())
        field.widget.attrs.update({'class': 'multiple-choice'})
        return field 
Example 19
Project: coursys   Author: sfu-fas   File: submission_filters.py    License: GNU General Public License v3.0 5 votes vote down vote up
def display_value(field): 
	""" 
	Returns the displayed value for this BoundField, as rendered in widgets. 
	""" 
	value = field_value(field)
	if isinstance(field.field, ChoiceField): 
		for (val, desc) in field.field.choices: 
			if val == value: 
				return desc 
	return value 
Example 20
Project: coursys   Author: sfu-fas   File: select.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        the_choices = [(k, v) for k, v in self.config.items() if k.startswith("choice_") and self.config[k]]
        the_choices = sorted(the_choices, key=lambda choice: (int) (re.findall(r'\d+', choice[0])[0]))

        c = forms.ChoiceField(required=self.config['required'],
            label=self.config['label'],
            help_text=self.config['help_text'],
            choices=the_choices,
            widget=forms.RadioSelect())

        if fieldsubmission:
            initial=fieldsubmission.data['info']
            c.initial=initial

        return c 
Example 21
Project: coursys   Author: sfu-fas   File: markup.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, with_wysiwyg=False, rows=20, default_markup='creole', allow_math=True, restricted=False,
                 max_length=100000, required=True, *args, **kwargs):
        choices = MARKUP_CHOICES_WYSIWYG if with_wysiwyg else MARKUP_CHOICES
        fields = [
            forms.CharField(required=required, max_length=max_length),
            forms.ChoiceField(choices=choices, required=True),
            forms.BooleanField(required=False),
        ]
        self.required = required
        self.force_display_required = required

        help_url = '/docs/markup' # hard-coded URL because lazy-evaluating them is hard
        default_help = '<a href="' + help_url + '">Markup language</a> used in the content'
        if allow_math:
            default_help += ', and should <a href="http://www.mathjax.org/">MathJax</a> be used for displaying TeX formulas?'
        default_help += ' <span id="markup-help"></span>'
        help_text = kwargs.pop('help_text', mark_safe(default_help))

        super(MarkupContentField, self).__init__(fields, required=False,
            help_text=help_text,
            *args, **kwargs)

        self.fields[0].required = required
        self.widget.widgets[0].attrs['rows'] = rows
        self.fields[1].required = required
        self.widget.widgets[1].choices = choices

        self.widget.allow_math = allow_math
        self.restricted = restricted
        self.widget.default_markup = default_markup 
Example 22
Project: coursys   Author: sfu-fas   File: search.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_operator_field(self, viewer, member_units):
        return forms.ChoiceField(choices=self.OPERATOR_CHOICES, label='', required=False) 
Example 23
Project: coursys   Author: sfu-fas   File: search.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_value_field(self, viewer, member_units):
        return forms.ChoiceField(choices=self.CHOICES, initial='', label='', required=False) 
Example 24
Project: coursys   Author: sfu-fas   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        fields = [forms.ChoiceField(), forms.CharField(max_length=8)]
        kwargs['fields'] = fields
        kwargs['widget'] = SupervisorWidget()
        super(SupervisorField, self).__init__(*args, **kwargs) 
Example 25
Project: StormOnline   Author: stormsha   File: dashboard.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 26
Project: StormOnline   Author: stormsha   File: dashboard.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, required=True, widget=None, label=None, initial=None,
                 help_text=None, *args, **kwargs):
        # Call Field instead of ChoiceField __init__() because we don't need
        # ChoiceField.__init__().
        forms.Field.__init__(self, required, widget, label, initial, help_text,
                             *args, **kwargs)
        self.widget.choices = self.choices 
Example 27
Project: heltour   Author: cyanfish   File: forms.py    License: MIT License 5 votes vote down vote up
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) 
Example 28
Project: heltour   Author: cyanfish   File: forms.py    License: MIT License 5 votes vote down vote up
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'] 
Example 29
Project: ideascube   Author: ideascube   File: forms.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        formats = getattr(settings, 'USER_IMPORT_FORMATS', None)

        if formats is None:
            self.fields['format'] = forms.CharField(
                required=True, initial='ideascube', widget=forms.HiddenInput)

        else:
            self.fields['format'] = forms.ChoiceField(
                required=True, initial=formats[0][0], choices=formats) 
Example 30
Project: kobo-predict   Author: awemulya   File: forms.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, project, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(SiteBulkEditForm, self).__init__(*args, **kwargs)

        self.fields['sites'] = forms.ModelMultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            queryset=project.sites.all(),
        )

        for attr in project.site_meta_attributes:
            q_type = attr['question_type']
            q_name = attr['question_name']

            if q_type == 'Number':
                field = forms.FloatField()
            elif q_type == 'Date':
                field = forms.DateField()
            elif q_type == 'MCQ':
                options = attr.get('mcq_options') or []
                choices = [o.get('option_text') for o in options]
                choices = [(c, c) for c in choices]
                field = forms.ChoiceField(choices=choices)
            else:
                field = forms.CharField()

            self.fields[q_name] = field