Python django.forms.ChoiceField() Examples
The following are 30
code examples of django.forms.ChoiceField().
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 also want to check out all available functions/classes of the module
django.forms
, or try the search function
.
Example #1
Source File: forms.py From yournextrepresentative with GNU Affero General Public License v3.0 | 7 votes |
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 #2
Source File: select.py From coursys with GNU General Public License v3.0 | 6 votes |
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
Source File: forms.py From boss with Apache License 2.0 | 6 votes |
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 #4
Source File: forms.py From heltour with MIT License | 6 votes |
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
Source File: forms.py From anytask with MIT License | 6 votes |
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 #6
Source File: base.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #7
Source File: admin.py From django-seo with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Source File: mc.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #9
Source File: forms_json.py From starthinker with Apache License 2.0 | 6 votes |
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 #10
Source File: notes.py From Servo with BSD 2-Clause "Simplified" License | 6 votes |
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 #11
Source File: registration.py From byro with Apache License 2.0 | 6 votes |
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 #12
Source File: test_fields.py From wagtailstreamforms with MIT License | 5 votes |
def test_dropdown_field(self): data = self.get_form_field_data("dropdown") cls = wsf_fields.DropdownField() field = cls.get_formfield(data) self.assertIsInstance(field, forms.ChoiceField) self.assertIsInstance(field.widget, forms.widgets.Select) self.assertEqual(field.label, data["label"]) self.assertEqual(field.required, data["required"]) self.assertEqual(field.help_text, data["help_text"]) self.assertEqual(field.choices, [(c, c) for c in data["choices"]]) data["empty_label"] = "Please Select" field = cls.get_formfield(data) self.assertEqual(field.choices[0], ("", "Please Select"))
Example #13
Source File: dashboard.py From myblog with GNU Affero General Public License v3.0 | 5 votes |
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 #14
Source File: forms.py From Spirit with MIT License | 5 votes |
def __init__(self, poll, user=None, *args, **kwargs): super(PollVoteManyForm, self).__init__(*args, **kwargs) self.auto_id = 'id_poll_{pk}_%s'.format(pk=poll.pk) # Uniqueness "<label for=id_poll_pk_..." self.user = user self.poll = poll self.poll_choices = getattr(poll, 'choices', poll.poll_choices.unremoved()) choices = ((c.pk, mark_safe(c.description)) for c in self.poll_choices) if poll.is_multiple_choice: self.fields['choices'] = forms.MultipleChoiceField( choices=choices, widget=forms.CheckboxSelectMultiple, label=_("Poll choices") ) else: self.fields['choices'] = forms.ChoiceField( choices=choices, widget=forms.RadioSelect, label=_("Poll choices") )
Example #15
Source File: test_fields.py From wagtailstreamforms with MIT License | 5 votes |
def test_radio_field(self): data = self.get_form_field_data("radio") cls = wsf_fields.RadioField() field = cls.get_formfield(data) self.assertIsInstance(field, forms.ChoiceField) self.assertIsInstance(field.widget, forms.widgets.RadioSelect) self.assertEqual(field.label, data["label"]) self.assertEqual(field.required, data["required"]) self.assertEqual(field.help_text, data["help_text"]) self.assertEqual(field.choices, [(c, c) for c in data["choices"]])
Example #16
Source File: forms.py From yournextrepresentative with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): election = kwargs.pop('election') post = kwargs.pop('post') super(AddCandidacyPickPartyForm, self).__init__(*args, **kwargs) party_set = PartySet.objects.get(postextra__slug=post) self.fields['party'] = \ forms.ChoiceField( label=_("Party in {election}").format( election=election.name, ), choices=party_set.party_choices(), required=False, widget=forms.Select( attrs={ 'class': 'party-select party-select-' + election.slug } ), ) if election.party_lists_in_use: # Then add a field to enter the position on the party list # as an integer: self.fields['party_list_position'] = forms.IntegerField( label=_("Position in party list ('1' for first, '2' for second, etc.)"), min_value=1, required=False, widget=forms.NumberInput( attrs={ 'class': 'party-position party-position-' + election.slug } ) )
Example #17
Source File: select.py From ontask_b with MIT License | 5 votes |
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)
Example #18
Source File: dashboard.py From django_OA with GNU General Public License v3.0 | 5 votes |
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 #19
Source File: forms.py From boss with Apache License 2.0 | 5 votes |
def PermField(): #perms = ['read', 'add', 'update', 'delete', 'assign_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])
Example #20
Source File: plugin.py From ontask_b with MIT License | 5 votes |
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
Example #21
Source File: dashboard.py From CTF_AWD_Platform with MIT License | 5 votes |
def __init__(self, *, required=True, widget=None, label=None, initial=None, help_text=None, **kwargs): # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). forms.Field.__init__(self, **kwargs) self.widget.choices = self.choices
Example #22
Source File: dashboard.py From CTF_AWD_Platform with MIT License | 5 votes |
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 #23
Source File: dashboard.py From myblog with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, *, required=True, widget=None, label=None, initial=None, help_text=None, **kwargs): # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). forms.Field.__init__(self, **kwargs) self.widget.choices = self.choices
Example #24
Source File: forms.py From urbanfootprint with GNU General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): initial_role = None role_choices = [] if 'initial_role' in kwargs: initial_role = kwargs.pop('initial_role') if 'role_choices' in kwargs: role_choices = kwargs.pop('role_choices') super(UserForm, self).__init__(*args, **kwargs) self.fields['role'] = forms.ChoiceField(choices=role_choices, widget=forms.Select(attrs={'class': 'form-control'})) if initial_role: self.fields['role'].initial = initial_role
Example #25
Source File: test_form_mixins.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def test_set_standard_field_with_single_lang(self): form_mixin = form_mixins.AttributeFormMixin() form_mixin.project = self.project form_mixin.fields = {'building': ChoiceField( choices=(('barn', 'Barn'), ('house', 'House')))} questionnaire = q_factories.QuestionnaireFactory( project=self.project) question = q_factories.QuestionFactory.create( type='S1', name='building', questionnaire=questionnaire, label='Name') q_factories.QuestionOptionFactory( question=question, name='barn', label='Barn', index=0) q_factories.QuestionOptionFactory( question=question, name='house', label='House', index=1) form_mixin.set_standard_field('building', empty_choice='Select house type') widget = form_mixin.fields['building'].widget assert isinstance(widget, XLangSelect) is True assert widget.choices == [ ('', 'Select house type'), ('barn', 'Barn'), ('house', 'House') ] assert widget.xlang_labels == {}
Example #26
Source File: test_form_mixins.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def test_set_standard_field_with_empty_choice(self): form_mixin = form_mixins.AttributeFormMixin() form_mixin.project = self.project form_mixin.fields = {'building': ChoiceField( choices=(('barn', 'Barn'), ('house', 'House')))} questionnaire = q_factories.QuestionnaireFactory( project=self.project, default_language='de') question = q_factories.QuestionFactory.create( type='S1', name='building', questionnaire=questionnaire, label={'en': 'Name', 'de': 'Name'}) q_factories.QuestionOptionFactory( question=question, name='barn', label={'de': 'Scheune', 'en': 'Barn'}, index=0) q_factories.QuestionOptionFactory( question=question, name='house', label={'de': 'Haus', 'en': 'Haus'}, index=1) form_mixin.set_standard_field('building', empty_choice='Select house type') widget = form_mixin.fields['building'].widget assert isinstance(widget, XLangSelect) is True assert widget.choices == [ ('', 'Select house type'), ('barn', 'Scheune'), ('house', 'Haus') ] assert widget.xlang_labels == { 'barn': {'de': 'Scheune', 'en': 'Barn'}, 'house': {'de': 'Haus', 'en': 'Haus'} }
Example #27
Source File: test_form_mixins.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def test_set_standard_field_with_options(self): form_mixin = form_mixins.AttributeFormMixin() form_mixin.project = self.project form_mixin.fields = {'building': ChoiceField( choices=(('barn', 'Barn'), ('house', 'House')))} questionnaire = q_factories.QuestionnaireFactory( project=self.project, default_language='de') question = q_factories.QuestionFactory.create( type='S1', name='building', questionnaire=questionnaire, label={'en': 'Name', 'de': 'Name'}) q_factories.QuestionOptionFactory( question=question, name='barn', label={'de': 'Scheune', 'en': 'Barn'}, index=0) q_factories.QuestionOptionFactory( question=question, name='house', label={'de': 'Haus', 'en': 'Haus'}, index=1) form_mixin.set_standard_field('building') widget = form_mixin.fields['building'].widget assert isinstance(widget, XLangSelect) is True assert widget.choices == [('barn', 'Scheune'), ('house', 'Haus')] assert widget.xlang_labels == { 'barn': {'de': 'Scheune', 'en': 'Barn'}, 'house': {'de': 'Haus', 'en': 'Haus'} }
Example #28
Source File: filters.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def display_choice_verbose(field): """Return the displayed value for this BoundField.""" if isinstance(field.field, ChoiceField): value = field_value(field) for (val, desc) in field.field.choices: if val == value: return desc
Example #29
Source File: documents.py From byro with Apache License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): initial_category = kwargs.pop("initial_category", "byro.documents.misc") super().__init__(*args, **kwargs) categories = get_document_category_names() self.fields["category"] = forms.ChoiceField( choices=sorted(categories.items()), initial=initial_category ) if "class" in self.fields["date"].widget.attrs: self.fields["date"].widget.attrs["class"] += " datepicker" else: self.fields["date"].widget.attrs["class"] = "datepicker"
Example #30
Source File: forms.py From SEMS with GNU General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): super(GradeStudentsForm, self).__init__(*args, **kwargs) # if course: # self.fields['student'].widget = forms.ChoiceField(choices=[(s.pk, s.first_name) for s in Student.objects.all()]) # self.fields['student'].widget = forms.ChoiceField(queryset=Student.objects.values_list('pk', 'first_name')) self.fields['student'].widget.attrs.update({'class': 'form-control'}) self.fields['grade'].widget.attrs.update({'class': 'form-control'})