Python django.forms.TypedChoiceField() Examples
The following are 30
code examples of django.forms.TypedChoiceField().
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 heltour with MIT License | 7 votes |
def __init__(self, league, player, *args, **kwargs): super(NotificationsForm, self).__init__(*args, **kwargs) for type_, _ in PLAYER_NOTIFICATION_TYPES: setting = PlayerNotificationSetting.get_or_default(player=player, league=league, type=type_) self.fields[type_ + "_lichess"] = forms.BooleanField(required=False, label="Lichess", initial=setting.enable_lichess_mail) self.fields[type_ + "_slack"] = forms.BooleanField(required=False, label="Slack", initial=setting.enable_slack_im) self.fields[type_ + "_slack_wo"] = forms.BooleanField(required=False, label="Slack (with opponent)", initial=setting.enable_slack_mpim) if type_ == 'before_game_time': offset_options = [(5, '5 minutes'), (10, '10 minutes'), (20, '20 minutes'), (30, '30 minutes'), (60, '1 hour'), (120, '2 hours')] self.fields[type_ + '_offset'] = forms.TypedChoiceField(choices=offset_options, initial=int( setting.offset.total_seconds()) / 60, coerce=int)
Example #2
Source File: forms.py From conf_site with MIT License | 7 votes |
def __init__(self, *args, **kwargs): super(ProposalVoteForm, self).__init__(*args, **kwargs) # Use a radio select widget instead of a dropdown for the score. self.fields["score"] = forms.TypedChoiceField( choices=ProposalVote.SCORES, coerce=int, empty_value=0, widget=forms.RadioSelect(), )
Example #3
Source File: forms.py From registrasion with Apache License 2.0 | 7 votes |
def set_fields(cls, category, products): choices = [] if not category.required: choices.append((0, "---")) for product in products: choice_text = "%s -- $%d each" % (product.name, product.price) choices.append((product.id, choice_text)) cls.base_fields[cls.CHOICE_FIELD] = forms.TypedChoiceField( label=category.name, widget=forms.Select, choices=choices, initial=0, empty_value=0, coerce=int, ) cls.base_fields[cls.QUANTITY_FIELD] = forms.IntegerField( label="Quantity", # TODO: internationalise min_value=0, max_value=500, # Issue #19. We should figure out real limit. )
Example #4
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_typedchoicefield_5(self): # Non-required fields aren't required f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual('', f.clean('')) # If you want cleaning an empty value to return a different type, tell the field
Example #5
Source File: fields.py From pasportaservo with GNU Affero General Public License v3.0 | 6 votes |
def formfield(self, **kwargs): class SuggestiveTypedChoiceFormField(forms.TypedChoiceField): widget = TextWithDatalistInput def to_python(self, value): value = super().to_python(value) if value not in self.empty_values: try: value = next(i for (i, choice) in self.choices if choice == value) except StopIteration: pass return value def validate(self, value): _handle_invalid_choice(self, value) defaults = {'choices_form_class': SuggestiveTypedChoiceFormField} defaults.update(kwargs) return super().formfield(**defaults)
Example #6
Source File: forms.py From registrasion with Apache License 2.0 | 6 votes |
def set_fields(cls, category, products): choices = [] for product in products: choice_text = "%s -- $%d" % (product.name, product.price) choices.append((product.id, choice_text)) if not category.required: choices.append((0, "No selection")) cls.base_fields[cls.FIELD] = forms.TypedChoiceField( label=category.name, widget=forms.RadioSelect, choices=choices, empty_value=0, coerce=int, )
Example #7
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) msg = "'Select a valid choice. 2 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('2')
Example #8
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertTrue(f.clean('-1'))
Example #9
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_4(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) msg = "'Select a valid choice. B is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('B') # Required fields require values with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('')
Example #10
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_has_changed(self): # has_changed should not trigger required validation f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=True) self.assertFalse(f.has_changed(None, '')) self.assertFalse(f.has_changed(1, '1')) self.assertFalse(f.has_changed('1', '1')) f = TypedChoiceField( choices=[('', '---------'), ('a', "a"), ('b', "b")], coerce=str, required=False, initial=None, empty_value=None, ) self.assertFalse(f.has_changed(None, '')) self.assertTrue(f.has_changed('', 'a')) self.assertFalse(f.has_changed('a', 'a'))
Example #11
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_special_coerce(self): """ A coerce function which results in a value not present in choices should raise an appropriate error (#21397). """ def coerce_func(val): return decimal.Decimal('1.%s' % val) f = TypedChoiceField(choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True) self.assertEqual(decimal.Decimal('1.2'), f.clean('2')) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('3')
Example #12
Source File: forms.py From edx-enterprise with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): """ Initialize the form. Substitutes CharField with TypedChoiceField for the provider_id field. """ super(EnterpriseCustomerIdentityProviderAdminForm, self).__init__(*args, **kwargs) idp_choices = utils.get_idp_choices() help_text = '' if saml_provider_configuration: provider_id = self.instance.provider_id url = reverse('admin:{}_{}_add'.format( saml_provider_configuration._meta.app_label, saml_provider_configuration._meta.model_name)) if provider_id: identity_provider = utils.get_identity_provider(provider_id) if identity_provider: update_url = url + '?source={}'.format(identity_provider.pk) help_text = '<p><a href="{update_url}" target="_blank">View "{identity_provider}" details</a><p>'.\ format(update_url=update_url, identity_provider=identity_provider.name) else: help_text += '<p style="margin-top:-5px;"> Make sure you have added a valid provider_id.</p>' else: help_text += '<p style="margin-top:-5px;"><a target="_blank" href={add_url}>' \ 'Create a new identity provider</a></p>'.format(add_url=url) if idp_choices is not None: self.fields['provider_id'] = forms.TypedChoiceField( choices=idp_choices, label=_('Identity Provider'), help_text=mark_safe(help_text), )
Example #13
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_2(self): # Different coercion, same validation. f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual(1.0, f.clean('1'))
Example #14
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertTrue(f.clean('-1'))
Example #15
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_5(self): # Non-required fields aren't required f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual('', f.clean('')) # If you want cleaning an empty value to return a different type, tell the field
Example #16
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_6(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None) self.assertIsNone(f.clean(''))
Example #17
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_has_changed(self): # has_changed should not trigger required validation f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=True) self.assertFalse(f.has_changed(None, '')) self.assertFalse(f.has_changed(1, '1')) self.assertFalse(f.has_changed('1', '1')) f = TypedChoiceField( choices=[('', '---------'), ('a', "a"), ('b', "b")], coerce=str, required=False, initial=None, empty_value=None, ) self.assertFalse(f.has_changed(None, '')) self.assertTrue(f.has_changed('', 'a')) self.assertFalse(f.has_changed('a', 'a'))
Example #18
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_special_coerce(self): """ A coerce function which results in a value not present in choices should raise an appropriate error (#21397). """ def coerce_func(val): return decimal.Decimal('1.%s' % val) f = TypedChoiceField(choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True) self.assertEqual(decimal.Decimal('1.2'), f.clean('2')) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('3')
Example #19
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_2(self): # Different coercion, same validation. f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual(1.0, f.clean('1'))
Example #20
Source File: test_typedchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) msg = "'Select a valid choice. 2 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('2')
Example #21
Source File: tests.py From TWLight with MIT License | 5 votes |
def test_application_optional_fields_match_field_type(self): """ The optional partner-specific data fields on Application should correspond to the FIELD_TYPES used on the form. Additionally, each should allow blank=True (since not all instances require all data), except for BooleanFields, which should default False (i.e. they should default to not requiring the data). """ for field in PARTNER_FORM_OPTIONAL_FIELDS: # Ensure Application fields allow for empty data. if not isinstance(Application._meta.get_field(field), models.BooleanField): self.assertTrue(Application._meta.get_field(field).blank) else: self.assertFalse(Application._meta.get_field(field).default) # Make sure the form fields we're using match what the model fields # can record. modelfield = Application._meta.get_field(field) formfield = modelfield.formfield() # While we simply use the ChoiceField for requested_access_duration field in the form, the model makes use # of the TypedChoiceField, triggering a mismatch. We'll get around this by separately testing the fields. if field == "requested_access_duration": self.assertEqual(type(formfield), forms.TypedChoiceField) self.assertEqual(type(FIELD_TYPES[field]), forms.ChoiceField) break self.assertEqual(type(formfield), type(FIELD_TYPES[field]))
Example #22
Source File: __init__.py From python2017 with MIT License | 5 votes |
def formfield(self, form_class=None, choices_form_class=None, **kwargs): """ Returns a django.forms.Field instance for this database Field. """ defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Fields with choices get special treatment. include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) defaults['choices'] = self.get_choices(include_blank=include_blank) defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial', 'disabled'): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults)
Example #23
Source File: __init__.py From openhgsenti with Apache License 2.0 | 5 votes |
def formfield(self, form_class=None, choices_form_class=None, **kwargs): """ Returns a django.forms.Field instance for this database Field. """ defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Fields with choices get special treatment. include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) defaults['choices'] = self.get_choices(include_blank=include_blank) defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults)
Example #24
Source File: __init__.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def formfield(self, form_class=forms.CharField, **kwargs): """ Returns a django.forms.Field instance for this database Field. """ defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Fields with choices get special treatment. include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) defaults['choices'] = self.get_choices(include_blank=include_blank) defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) return form_class(**defaults)
Example #25
Source File: __init__.py From python with Apache License 2.0 | 5 votes |
def formfield(self, form_class=None, choices_form_class=None, **kwargs): """ Returns a django.forms.Field instance for this database Field. """ defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Fields with choices get special treatment. include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) defaults['choices'] = self.get_choices(include_blank=include_blank) defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial', 'disabled'): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults)
Example #26
Source File: __init__.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def formfield(self, form_class=None, choices_form_class=None, **kwargs): """Return a django.forms.Field instance for this field.""" defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Fields with choices get special treatment. include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) defaults['choices'] = self.get_choices(include_blank=include_blank) defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial', 'disabled'): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults)
Example #27
Source File: django_field_methods.py From django-cassandra-engine with BSD 2-Clause "Simplified" License | 5 votes |
def formfield(self, form_class=None, choices_form_class=None, **kwargs): # Taken from django.db.models.fields.__init__ defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default: if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Fields with choices get special treatment. include_blank = (self.blank or not (self.has_default or 'initial' in kwargs)) defaults['choices'] = self.get_choices(include_blank=include_blank) defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults)
Example #28
Source File: __init__.py From bioforum with MIT License | 5 votes |
def formfield(self, form_class=None, choices_form_class=None, **kwargs): """Return a django.forms.Field instance for this field.""" defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Fields with choices get special treatment. include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) defaults['choices'] = self.get_choices(include_blank=include_blank) defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial', 'disabled'): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults)
Example #29
Source File: forms.py From anytask with MIT License | 5 votes |
def get_status_form(field_name, request, issue, data=None, *args, **kwargs): class _form(DefaultForm): lang = request.user.profile.language status = forms.TypedChoiceField(get_status_choice(issue, lang), coerce=status_id2status, label='', required=False) return _form(field_name, request, issue, data, *args, **kwargs)
Example #30
Source File: forms.py From anytask with MIT License | 5 votes |
def get_responsible_form(field_name, request, issue, data=None, *args, **kwargs): class _form(DefaultForm): responsible_name = forms.TypedChoiceField(get_users_choise(issue, 'responsible'), coerce=user_id2user, label='', required=False) return _form(field_name, request, issue, data, *args, **kwargs)