Python django.forms.utils.ErrorList() Examples

The following are 30 code examples of django.forms.utils.ErrorList(). 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.utils , or try the search function .
Example #1
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_block_level_validation_renders_errors(self):
        block = FooStreamBlock()

        post_data = {'stream-count': '2'}
        for i, value in enumerate(['bar', 'baz']):
            post_data.update({
                'stream-%d-deleted' % i: '',
                'stream-%d-order' % i: str(i),
                'stream-%d-type' % i: 'text',
                'stream-%d-value' % i: value,
            })

        block_value = block.value_from_datadict(post_data, {}, 'stream')
        with self.assertRaises(ValidationError) as catcher:
            block.clean(block_value)

        errors = ErrorList([
            catcher.exception
        ])

        self.assertInHTML(
            format_html('<div class="help-block help-critical">{}</div>', FooStreamBlock.error),
            block.render_form(block_value, prefix='stream', errors=errors)) 
Example #2
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_errorlist_override(self):
        class DivErrorList(ErrorList):
            def __str__(self):
                return self.as_divs()

            def as_divs(self):
                if not self:
                    return ''
                return '<div class="errorlist">%s</div>' % ''.join(
                    '<div class="error">%s</div>' % e for e in self)

        class CommentForm(Form):
            name = CharField(max_length=50, required=False)
            email = EmailField()
            comment = CharField()

        data = {'email': 'invalid'}
        f = CommentForm(data, auto_id=False, error_class=DivErrorList)
        self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50"></p>
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
<p>Email: <input type="email" name="email" value="invalid" required></p>
<div class="errorlist"><div class="error">This field is required.</div></div>
<p>Comment: <input type="text" name="comment" required></p>""") 
Example #3
Source File: test_utils.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_error_dict_copy(self):
        e = ErrorDict()
        e['__all__'] = ErrorList([
            ValidationError(
                message='message %(i)s',
                params={'i': 1},
            ),
            ValidationError(
                message='message %(i)s',
                params={'i': 2},
            ),
        ])

        e_copy = copy.copy(e)
        self.assertEqual(e, e_copy)
        self.assertEqual(e.as_data(), e_copy.as_data())

        e_deepcopy = copy.deepcopy(e)
        self.assertEqual(e, e_deepcopy)
        self.assertEqual(e.as_data(), e_copy.as_data()) 
Example #4
Source File: list_block.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def clean(self, value):
        result = []
        errors = []
        for child_val in value:
            try:
                result.append(self.child_block.clean(child_val))
            except ValidationError as e:
                errors.append(ErrorList([e]))
            else:
                errors.append(None)

        if any(errors):
            # The message here is arbitrary - outputting error messages is delegated to the child blocks,
            # which only involves the 'params' list
            raise ValidationError('Validation error in ListBlock', params=errors)

        return result 
Example #5
Source File: forms.py    From micro-finance with MIT License 6 votes vote down vote up
def clean(self):
        if self.cleaned_data.get("recurring_deposit_account_no"):
            self.recurring_deposit_account = RecurringDeposits.objects.filter(
                client=self.client,
                reccuring_deposit_number=self.cleaned_data.get("recurring_deposit_account_no")
            ).last()
        if not self.recurring_deposit_account:
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append(
                "No Recurring Deposit Accounts found with given a/c number")
            raise forms.ValidationError(errors)
        elif self.recurring_deposit_account.status == 'Closed':
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append("Member Recurring Deposit is Closed.")
            raise forms.ValidationError(errors)
        return self.cleaned_data 
Example #6
Source File: forms.py    From micro-finance with MIT License 6 votes vote down vote up
def clean(self):
        self.client = None
        self.pay_type = self.cleaned_data.get('payment_type')
        if not(self.cleaned_data.get("client_name") and self.cleaned_data.get("client_account_number")):
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append("Please provide both  member first name, account number")
            raise forms.ValidationError(errors)
        self.client = Client.objects.filter(
            first_name__iexact=self.cleaned_data.get("client_name"),
            account_number=self.cleaned_data.get("client_account_number")
        ).last()
        if not self.client:
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append("No Client exists with this First Name and Account number.")
            raise forms.ValidationError(errors)
        return self.cleaned_data 
Example #7
Source File: forms.py    From micro-finance with MIT License 6 votes vote down vote up
def clean(self):

        if self.cleaned_data.get("recurring_deposit_account_no"):
            self.recurring_deposit_account = RecurringDeposits.objects.filter(
                reccuring_deposit_number=self.cleaned_data.get("recurring_deposit_account_no")).last()
        if not self.recurring_deposit_account:
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append("No Recurring Deposit Accounts found with given a/c number")
            raise forms.ValidationError(errors)
        if self.recurring_deposit_account.status == "Paid":
            errors = self.errors.setdefault('message1', ErrorList())
            errors.append('Member Recurring Deposit already paid')
            raise forms.ValidationError(errors)
        elif self.recurring_deposit_account.status == 'Closed':
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append("Member Recurring Deposit is Closed.")
            raise forms.ValidationError(errors)
        return self.cleaned_data 
Example #8
Source File: forms.py    From micro-finance with MIT License 6 votes vote down vote up
def clean(self):
        if self.cleaned_data.get("fixed_deposit_account_no"):
            self.fixed_deposit_account = FixedDeposits.objects.filter(
                fixed_deposit_number=self.cleaned_data.get("fixed_deposit_account_no")).last()
        if not self.fixed_deposit_account:
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append("No Fixed Deposit Accounts found with given a/c number")
            raise forms.ValidationError(errors)
        if self.fixed_deposit_account.status == "Paid":
            errors = self.errors.setdefault('message1', ErrorList())
            errors.append('Member Fixed Deposit already paid')
            raise forms.ValidationError(errors)
        elif self.fixed_deposit_account.status == 'Closed':
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append("Member Fixed Deposit is Closed.")
            raise forms.ValidationError(errors)
        return self.cleaned_data 
Example #9
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_error_class(self):
        '''
        Test the type of Formset and Form error attributes
        '''
        Formset = modelformset_factory(User, fields="__all__")
        data = {
            'form-TOTAL_FORMS': '2',
            'form-INITIAL_FORMS': '0',
            'form-MAX_NUM_FORMS': '0',
            'form-0-id': '',
            'form-0-username': 'apollo13',
            'form-0-serial': '1',
            'form-1-id': '',
            'form-1-username': 'apollo13',
            'form-1-serial': '2',
        }
        formset = Formset(data)
        # check if the returned error classes are correct
        # note: formset.errors returns a list as documented
        self.assertIsInstance(formset.errors, list)
        self.assertIsInstance(formset.non_form_errors(), ErrorList)
        for form in formset.forms:
            self.assertIsInstance(form.errors, ErrorDict)
            self.assertIsInstance(form.non_field_errors(), ErrorList) 
Example #10
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_error_list(self):
        e = ErrorList()
        e.append('Foo')
        e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'}))

        self.assertIsInstance(e, list)
        self.assertIn('Foo', e)
        self.assertIn('Foo', forms.ValidationError(e))

        self.assertEqual(
            e.as_text(),
            '* Foo\n* Foobar'
        )

        self.assertEqual(
            e.as_ul(),
            '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
        )

        errors = e.get_json_data()
        self.assertEqual(
            errors,
            [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}]
        )
        self.assertEqual(json.dumps(errors), e.as_json()) 
Example #11
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_error_list(self):
        e = ErrorList()
        e.append('Foo')
        e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'}))

        self.assertIsInstance(e, list)
        self.assertIn('Foo', e)
        self.assertIn('Foo', forms.ValidationError(e))

        self.assertEqual(
            e.as_text(),
            '* Foo\n* Foobar'
        )

        self.assertEqual(
            e.as_ul(),
            '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
        )

        errors = e.get_json_data()
        self.assertEqual(
            errors,
            [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}]
        )
        self.assertEqual(json.dumps(errors), e.as_json()) 
Example #12
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_raises_custom_error_message(self):
        test_message = 'Not a valid library card number.'
        block = blocks.RegexBlock(regex=r'^[0-9]{3}$', error_messages={
            'invalid': test_message
        })

        with self.assertRaises(ValidationError) as context:
            block.clean("[/]")

        self.assertIn(test_message, context.exception.messages)

        html = block.render_form(
            "[/]",
            errors=ErrorList([ValidationError(test_message)]))

        self.assertIn(test_message, html) 
Example #13
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_errorlist_override(self):
        class DivErrorList(ErrorList):
            def __str__(self):
                return self.as_divs()

            def as_divs(self):
                if not self:
                    return ''
                return '<div class="errorlist">%s</div>' % ''.join(
                    '<div class="error">%s</div>' % e for e in self)

        class CommentForm(Form):
            name = CharField(max_length=50, required=False)
            email = EmailField()
            comment = CharField()

        data = {'email': 'invalid'}
        f = CommentForm(data, auto_id=False, error_class=DivErrorList)
        self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50"></p>
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
<p>Email: <input type="email" name="email" value="invalid" required></p>
<div class="errorlist"><div class="error">This field is required.</div></div>
<p>Comment: <input type="text" name="comment" required></p>""") 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_error_class(self):
        '''
        Test the type of Formset and Form error attributes
        '''
        Formset = modelformset_factory(User, fields="__all__")
        data = {
            'form-TOTAL_FORMS': '2',
            'form-INITIAL_FORMS': '0',
            'form-MAX_NUM_FORMS': '0',
            'form-0-id': '',
            'form-0-username': 'apollo13',
            'form-0-serial': '1',
            'form-1-id': '',
            'form-1-username': 'apollo13',
            'form-1-serial': '2',
        }
        formset = Formset(data)
        # check if the returned error classes are correct
        # note: formset.errors returns a list as documented
        self.assertIsInstance(formset.errors, list)
        self.assertIsInstance(formset.non_form_errors(), ErrorList)
        for form in formset.forms:
            self.assertIsInstance(form.errors, ErrorDict)
            self.assertIsInstance(form.non_field_errors(), ErrorList) 
Example #15
Source File: forms.py    From ecommerce with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList,
                 label_suffix=None, empty_permitted=False, instance=None, request=None):
        initial = initial or {}
        self.request = request
        if instance:
            initial.update({
                'program_uuid': instance.condition.program_uuid,
                'benefit_type': instance.benefit.proxy().benefit_class_type,
                'benefit_value': instance.benefit.value,
            })
        super(ProgramOfferForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix,
                                               empty_permitted, instance)

        date_ui_class = {'class': 'add-pikaday'}
        self.fields['start_datetime'].widget.attrs.update(date_ui_class)
        self.fields['end_datetime'].widget.attrs.update(date_ui_class) 
Example #16
Source File: forms.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=None,
                 empty_permitted=False):
        self.is_bound = data is not None or files is not None
        self.data = data or {}
        self.files = files or {}
        self.auto_id = auto_id
        self.prefix = prefix
        self.initial = initial or {}
        self.error_class = error_class
        # Translators: This is the default suffix added to form field labels
        self.label_suffix = label_suffix if label_suffix is not None else _(':')
        self.empty_permitted = empty_permitted
        self._errors = None  # Stores the errors after clean() has been called.
        self._changed_data = None

        # The base_fields class attribute is the *class-wide* definition of
        # fields. Because a particular *instance* of the class might want to
        # alter self.fields, we create self.fields here by copying base_fields.
        # Instances should always modify self.fields; they should not modify
        # self.base_fields.
        self.fields = copy.deepcopy(self.base_fields)
        self._bound_fields_cache = {} 
Example #17
Source File: __init__.py    From Kiwi with GNU General Public License v2.0 6 votes vote down vote up
def __init__(  # pylint: disable=too-many-arguments
            self, data=None, files=None, auto_id='id_%s', prefix=None,
            initial=None, error_class=ErrorList, label_suffix=None,
            empty_permitted=False, instance=None, use_required_attribute=None,
            renderer=None):
        super().__init__(
            data, files, auto_id, prefix,
            initial, error_class, label_suffix,
            empty_permitted, instance, use_required_attribute,
            renderer,
        )

        for field in self.fields:
            self.fields[field].required = False
            # will cause BaseForm._clean_fields() to reuse the value
            # from self.initial (<-- self.instance) if not specified
            self.fields[field].disabled = field not in data 
Example #18
Source File: forms.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None,
                 offering=None, userid=None, enforced_prep_min=0):
        super(TUGForm, self).__init__(data, files, auto_id, prefix, initial,
                 error_class, label_suffix, empty_permitted, instance)
        # see old revisions (git id 1d1d2f9) for a dropdown
        if userid is not None and offering is not None:
            member = Member.objects.exclude(role='DROP').get(person__userid=userid, offering=offering)
        elif instance is not None:
            member = instance.member
        else:
            assert False

        self.enforced_prep_min = enforced_prep_min

        self.initial['member'] = member
        self.fields['member'].widget = forms.widgets.HiddenInput()
        
        self.subforms = self.__construct_subforms(data, initial, instance) 
Example #19
Source File: config_forms.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean_sub_fields(self, value):
        """'value' being the list of the values of the subfields, validate
        each subfield."""
        clean_data = []
        errors = ErrorList()
        # Remove the field corresponding to the SKIP_CHECK_NAME boolean field
        # if required.
        fields = self.fields if not self.skip_check else self.fields[:-1]
        for index, field in enumerate(fields):
            try:
                field_value = value[index]
            except IndexError:
                field_value = None
            # Set the field_value to the default value if not set.
            if field_value is None and field.initial not in (None, ""):
                field_value = field.initial
            # Check the field's 'required' field instead of the global
            # 'required' field to allow subfields to be required or not.
            if field.required and field_value in validators.EMPTY_VALUES:
                errors.append(
                    "%s: %s" % (field.label, self.error_messages["required"])
                )
                continue
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(
                    "%s: %s" % (field.label, message) for message in e.messages
                )
        if errors:
            raise ValidationError(errors)

        out = self.compress(clean_data)
        self.validate(out)
        return out 
Example #20
Source File: blocks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_error_to_child(self, errors, child_number, field, message):
        new_error = ErrorList([message])
        try:
            errors[child_number].data[0].params[field] = new_error
        except KeyError:
            errors[child_number] = ErrorList(
                [ValidationError('Error', params={field: new_error})]
            ) 
Example #21
Source File: signup.py    From mitoc-trips with GNU General Public License v3.0 5 votes vote down vote up
def form_valid(self, form):
        signup = form.save(commit=False)
        signup.participant = self.request.participant

        errors = self.get_errors(signup)
        if errors:
            form.errors['__all__'] = ErrorList(errors)
            return self.form_invalid(form)
        return super().form_valid(form) 
Example #22
Source File: itinerary.py    From mitoc-trips with GNU General Public License v3.0 5 votes vote down vote up
def form_valid(self, form):
        if not self.trip.info_editable:
            verb = "modified" if self.trip.info else "created"
            form.errors['__all__'] = ErrorList([f"Itinerary cannot be {verb}"])
            return self.form_invalid(form)
        self.trip.info = form.save()
        self.trip.save()
        return super().form_valid(form) 
Example #23
Source File: test_utils.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_error_list_html_safe(self):
        e = ErrorList(['Invalid username.'])
        self.assertTrue(hasattr(ErrorList, '__html__'))
        self.assertEqual(str(e), e.__html__()) 
Example #24
Source File: list_block.py    From wagtail-react-streamfield with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean(self, value):
        result = []
        errors = []
        for child_val in value:
            try:
                result.append(self.child_block.clean(child_val))
            except ValidationError as e:
                errors.append(ErrorList([e]))
            else:
                errors.append(None)

        if any(errors):
            raise ValidationError('Validation error in ListBlock',
                                  params=errors)

        if self.meta.min_num is not None and self.meta.min_num > len(value):
            raise ValidationError(
                _('The minimum number of items is %d') % self.meta.min_num
            )
        elif self.required and len(value) == 0:
            raise ValidationError(_('This field is required.'))

        if self.meta.max_num is not None and self.meta.max_num < len(value):
            raise ValidationError(
                _('The maximum number of items is %d') % self.meta.max_num
            )

        return result 
Example #25
Source File: widgets.py    From wagtail-react-streamfield with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_non_block_errors(errors):
    if errors is None:
        return ()
    errors_data = errors.as_data()
    if isinstance(errors, ErrorList):
        errors_data = errors_data[0].params
        if errors_data is None:
            return errors
    if isinstance(errors_data, dict):
        return errors_data.get(NON_FIELD_ERRORS, ())
    return () 
Example #26
Source File: forms.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList,
                 label_suffix=None, empty_permitted=False, instance=None, request=None):
        initial = initial or {}
        self.request = request
        if instance:
            contract_discount_type, contract_discount_value, prepaid_invoice_amount = self._prep_contract_metadata(
                instance.enterprise_contract_metadata
            )
            initial.update({
                'enterprise_customer_uuid': instance.condition.enterprise_customer_uuid,
                'enterprise_customer_catalog_uuid': instance.condition.enterprise_customer_catalog_uuid,
                'benefit_type': instance.benefit.proxy().benefit_class_type,
                'benefit_value': instance.benefit.value,
                'contract_discount_type': contract_discount_type,
                'contract_discount_value': contract_discount_value,
                'prepaid_invoice_amount': prepaid_invoice_amount,
            })
        super(EnterpriseOfferForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix,
                                                  empty_permitted, instance)

        date_ui_class = {'class': 'add-pikaday'}
        self.fields['start_datetime'].widget.attrs.update(date_ui_class)
        self.fields['end_datetime'].widget.attrs.update(date_ui_class)
        # set the min attribute on input widget to enforce minimum value validation at frontend
        self.fields['max_discount'].widget.attrs.update({'min': 0})
        self.fields['max_user_discount'].widget.attrs.update({'min': 0}) 
Example #27
Source File: forms.py    From product-database with MIT License 5 votes vote down vote up
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList,
                 label_suffix=None, empty_permitted=False, instance=None):
        super().__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance)
        if instance:
            self.fields["product_id"].initial = instance.product.product_id 
Example #28
Source File: formsets.py    From python2017 with MIT License 5 votes vote down vote up
def non_form_errors(self):
        """
        Returns an ErrorList of errors that aren't associated with a particular
        form -- i.e., from formset.clean(). Returns an empty ErrorList if there
        are none.
        """
        if self._non_form_errors is None:
            self.full_clean()
        return self._non_form_errors 
Example #29
Source File: formsets.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, form_kwargs=None):
        self.is_bound = data is not None or files is not None
        self.prefix = prefix or self.get_default_prefix()
        self.auto_id = auto_id
        self.data = data or {}
        self.files = files or {}
        self.initial = initial
        self.form_kwargs = form_kwargs or {}
        self.error_class = error_class
        self._errors = None
        self._non_form_errors = None 
Example #30
Source File: models.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=None,
                 empty_permitted=False, instance=None, use_required_attribute=None):
        opts = self._meta
        if opts.model is None:
            raise ValueError('ModelForm has no model class specified.')
        if instance is None:
            # if we didn't get an instance, instantiate a new one
            self.instance = opts.model()
            object_data = {}
        else:
            self.instance = instance
            object_data = model_to_dict(instance, opts.fields, opts.exclude)
        # if initial was provided, it should override the values from instance
        if initial is not None:
            object_data.update(initial)
        # self._validate_unique will be set to True by BaseModelForm.clean().
        # It is False by default so overriding self.clean() and failing to call
        # super will stop validate_unique from being called.
        self._validate_unique = False
        super(BaseModelForm, self).__init__(
            data, files, auto_id, prefix, object_data, error_class,
            label_suffix, empty_permitted, use_required_attribute=use_required_attribute,
        )
        for formfield in self.fields.values():
            apply_limit_choices_to_to_formfield(formfield)