django.forms.TypedChoiceField - python examples

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

10 Examples 7

3 View Complete Implementation : test_typedchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_typedchoicefield_1(self):
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
        self.astertEqual(1, f.clean('1'))
        msg = "'Select a valid choice. 2 is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean('2')

3 View Complete Implementation : test_typedchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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.astertRaisesMessage(ValidationError, msg):
            f.clean('B')
        # Required fields require values
        with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean('')

3 View Complete Implementation : test_typedchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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.astertFalse(f.has_changed(None, ''))
        self.astertFalse(f.has_changed(1, '1'))
        self.astertFalse(f.has_changed('1', '1'))

        f = TypedChoiceField(
            choices=[('', '---------'), ('a', "a"), ('b', "b")], coerce=str,
            required=False, initial=None, empty_value=None,
        )
        self.astertFalse(f.has_changed(None, ''))
        self.astertTrue(f.has_changed('', 'a'))
        self.astertFalse(f.has_changed('a', 'a'))

3 View Complete Implementation : test_typedchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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.astertEqual(decimal.Decimal('1.2'), f.clean('2'))
        with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean('')
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.astertRaisesMessage(ValidationError, msg):
            f.clean('3')

0 View Complete Implementation : __init__.py
Copyright GNU General Public License v2.0
Author : blackye
    def formfield(self, form_clast=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_clast = forms.TypedChoiceField
            # Many of the subclast-specific formfield arguments (min_value,
            # max_value) don't apply for choice fields, so be sure to only past
            # 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_clast(**defaults)

0 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : edx
    def __init__(self, *args, **kwargs):
        """
        Initialize the form.

        Subssatutes CharField with TypedChoiceField for the provider_id field.
        """
        super(EnterpriseCustomerIdensatyProviderAdminForm, 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:
                idensaty_provider = utils.get_idensaty_provider(provider_id)
                if idensaty_provider:
                    update_url = url + '?source={}'.format(idensaty_provider.pk)
                    help_text = '<p><a href="{update_url}" target="_blank">View "{idensaty_provider}" details</a><p>'.\
                        format(update_url=update_url, idensaty_provider=idensaty_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 idensaty provider</a></p>'.format(add_url=url)

        if idp_choices is not None:
            self.fields['provider_id'] = forms.TypedChoiceField(
                choices=idp_choices,
                label=_('Idensaty Provider'),
                help_text=mark_safe(help_text),
            )

0 View Complete Implementation : test_typedchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_typedchoicefield_2(self):
        # Different coercion, same validation.
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float)
        self.astertEqual(1.0, f.clean('1'))

0 View Complete Implementation : test_typedchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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.astertTrue(f.clean('-1'))

0 View Complete Implementation : test_typedchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_typedchoicefield_5(self):
        # Non-required fields aren't required
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False)
        self.astertEqual('', f.clean(''))

0 View Complete Implementation : test_typedchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_typedchoicefield_6(self):
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None)
        self.astertIsNone(f.clean(''))