Python django.core.exceptions.NON_FIELD_ERRORS Examples

The following are 30 code examples of django.core.exceptions.NON_FIELD_ERRORS(). 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.core.exceptions , or try the search function .
Example #1
Source File: mixins.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def analyze_password(self, password_field_value):
        insecure, howmuch = is_password_compromised(password_field_value)

        if insecure and howmuch > 99:
            self.add_error(NON_FIELD_ERRORS, ValidationError(_(
                "The password selected by you is too insecure. "
                "Such combination of characters is very well-known to cyber-criminals."),
                code='compromised_password'))
            self.add_error(self.analyze_password_field, _("Choose a less easily guessable password."))
        elif insecure and howmuch > 1:
            self.add_error(NON_FIELD_ERRORS, ValidationError(_(
                "The password selected by you is not very secure. "
                "Such combination of characters is known to cyber-criminals."),
                code='compromised_password'))
            self.add_error(self.analyze_password_field, _("Choose a less easily guessable password."))

        if insecure:
            auth_log.warning(
                "Password with HIBP count {:d} selected in {}.".format(howmuch, self.__class__.__name__),
                extra={'request': self.view_request} if hasattr(self, 'view_request') else None,
            ) 
Example #2
Source File: messages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def validation_error(request, message, form, buttons=None):
    if not form.non_field_errors():
        # just output the generic "there were validation errors" message, and leave
        # the per-field highlighting to do the rest
        detail = ''
    else:
        # display the full list of field and non-field validation errors
        all_errors = []
        for field_name, errors in form.errors.items():
            if field_name == NON_FIELD_ERRORS:
                prefix = ''
            else:
                try:
                    field_label = form[field_name].label
                except KeyError:
                    field_label = field_name
                prefix = "%s: " % field_label

            for error in errors:
                all_errors.append(prefix + error)

        errors_html = format_html_join('\n', '<li>{}</li>', ((e,) for e in all_errors))
        detail = format_html("""<ul class="errorlist">{}</ul>""", errors_html)

    return messages.error(request, render(message, buttons, detail=detail)) 
Example #3
Source File: models.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def _post_clean(self):
        opts = self._meta
        # Update the model instance with self.cleaned_data.
        self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)

        exclude = self._get_validation_exclusions()

        # Foreign Keys being used to represent inline relationships
        # are excluded from basic field value validation. This is for two
        # reasons: firstly, the value may not be supplied (#12507; the
        # case of providing new values to the admin); secondly the
        # object being referred to may not yet fully exist (#12749).
        # However, these fields *must* be included in uniqueness checks,
        # so this can't be part of _get_validation_exclusions().
        for f_name, field in self.fields.items():
            if isinstance(field, InlineForeignKeyField):
                exclude.append(f_name)

        # Clean the model instance's fields.
        try:
            self.instance.clean_fields(exclude=exclude)
        except ValidationError as e:
            self._update_errors(e.message_dict)

        # Call the model instance's clean method.
        try:
            self.instance.clean()
        except ValidationError as e:
            self._update_errors({NON_FIELD_ERRORS: e.messages})

        # Validate uniqueness if needed.
        if self._validate_unique:
            self.validate_unique() 
Example #4
Source File: test_utils.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_ValidationError(self):
        exception = ValidationError({NON_FIELD_ERRORS: "Some error"})
        self.assertEqual(
            utils.get_error_message_for_exception(exception), "Some error"
        ) 
Example #5
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _update_errors(self, errors):
        """Provide Django 1.11-like behaviour in 1.8 as well."""
        if hasattr(errors, "error_dict"):
            error_dict = errors
        else:
            error_dict = ValidationError({NON_FIELD_ERRORS: errors})
        super()._update_errors(error_dict) 
Example #6
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_custom_validate_method(self):
        mtv = ModelToValidate(number=11)
        self.assertFailsValidation(mtv.full_clean, [NON_FIELD_ERRORS, 'name']) 
Example #7
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_has_error(self):
        class UserRegistration(Form):
            username = CharField(max_length=10)
            password1 = CharField(widget=PasswordInput, min_length=5)
            password2 = CharField(widget=PasswordInput)

            def clean(self):
                if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
                        self.cleaned_data['password1'] != self.cleaned_data['password2']):
                    raise ValidationError(
                        'Please make sure your passwords match.',
                        code='password_mismatch',
                    )

        f = UserRegistration(data={})
        self.assertTrue(f.has_error('password1'))
        self.assertTrue(f.has_error('password1', 'required'))
        self.assertFalse(f.has_error('password1', 'anything'))

        f = UserRegistration(data={'password1': 'Hi', 'password2': 'Hi'})
        self.assertTrue(f.has_error('password1'))
        self.assertTrue(f.has_error('password1', 'min_length'))
        self.assertFalse(f.has_error('password1', 'anything'))
        self.assertFalse(f.has_error('password2'))
        self.assertFalse(f.has_error('password2', 'anything'))

        f = UserRegistration(data={'password1': 'Bonjour', 'password2': 'Hello'})
        self.assertFalse(f.has_error('password1'))
        self.assertFalse(f.has_error('password1', 'required'))
        self.assertTrue(f.has_error(NON_FIELD_ERRORS))
        self.assertTrue(f.has_error(NON_FIELD_ERRORS, 'password_mismatch'))
        self.assertFalse(f.has_error(NON_FIELD_ERRORS, 'anything')) 
Example #8
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_custom_validate_method(self):
        mtv = ModelToValidate(number=11)
        self.assertFailsValidation(mtv.full_clean, [NON_FIELD_ERRORS, 'name']) 
Example #9
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 #10
Source File: base.py    From silver with Apache License 2.0 5 votes vote down vote up
def clean(self):
        super(BillingDocumentBase, self).clean()

        # The only change that is allowed if the document is in issued state
        # is the state chage from issued to paid
        # !! TODO: If _last_state == 'issued' and self.state == 'paid' || 'canceled'
        # it should also be checked that the other fields are the same bc.
        # right now a document can be in issued state and someone could
        # send a request which contains the state = 'paid' and also send
        # other changed fields and the request would be accepted bc. only
        # the state is verified.
        if self._last_state == self.STATES.ISSUED and\
           self.state not in [self.STATES.PAID, self.STATES.CANCELED]:
            msg = 'You cannot edit the document once it is in issued state.'
            raise ValidationError({NON_FIELD_ERRORS: msg})

        if self._last_state == self.STATES.CANCELED:
            msg = 'You cannot edit the document once it is in canceled state.'
            raise ValidationError({NON_FIELD_ERRORS: msg})

        # If it's in paid state => don't allow any changes
        if self._last_state == self.STATES.PAID:
            msg = 'You cannot edit the document once it is in paid state.'
            raise ValidationError(msg)

        if self.transactions.exclude(currency=self.transaction_currency).exists():
            message = 'There are unfinished transactions of this document that use a ' \
                      'different currency.'
            raise ValidationError({'transaction_currency': message}) 
Example #11
Source File: serializers.py    From silver with Apache License 2.0 5 votes vote down vote up
def django_to_drf_validation_error(django_validation_error,
                                   default_errors_key=None):
    try:
        errors = django_validation_error.message_dict
    except AttributeError:
        errors = django_validation_error.messages
        if default_errors_key:
            errors = {default_errors_key: errors}
    else:
        non_field_errors = errors.pop(NON_FIELD_ERRORS, None)
        if non_field_errors:
            errors[default_errors_key or api_settings.NON_FIELD_ERRORS_KEY] = non_field_errors

    raise serializers.ValidationError(errors) 
Example #12
Source File: payment_methods_serializers.py    From silver with Apache License 2.0 5 votes vote down vote up
def validate(self, attrs):
        attrs = super(PaymentMethodSerializer, self).validate(attrs)

        if self.instance:
            if self.instance.canceled:
                raise ValidationError(
                    'You cannot update a canceled payment method.'
                )

            # Run model clean and handle ValidationErrors
            try:
                # Use the existing instance to avoid unique field errors
                payment_method = self.instance
                payment_method_dict = payment_method.__dict__.copy()

                for attribute, value in attrs.items():
                    setattr(payment_method, attribute, value)

                payment_method.full_clean()

                # Revert changes to existing instance
                payment_method.__dict__ = payment_method_dict
            except ValidationError as e:
                errors = e.error_dict
                non_field_errors = errors.pop(NON_FIELD_ERRORS, None)
                if non_field_errors:
                    errors['non_field_errors'] = [
                        error for sublist in non_field_errors for error in sublist
                    ]
                raise serializers.ValidationError(errors)

        return attrs 
Example #13
Source File: forms.py    From scirius with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(RulesetChoiceForm, self).__init__(*args, **kwargs)
        ruleset_list =  Ruleset.objects.all()
        self.fields['rulesets'].queryset = ruleset_list

        if hasattr(self, 'rulesets_label'):
            self.fields['rulesets'].label = self.rulesets_label

        if not len(ruleset_list):
            if not (isinstance(self, AddSourceForm) or isinstance(self, AddPublicSourceForm)):
                self.errors[NON_FIELD_ERRORS] = ['Please create a ruleset first']
            self.fields.pop('rulesets') 
Example #14
Source File: forms.py    From python2017 with MIT License 5 votes vote down vote up
def non_field_errors(self):
        """
        Returns an ErrorList of errors that aren't associated with a particular
        field -- i.e., from Form.clean(). Returns an empty ErrorList if there
        are none.
        """
        return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield')) 
Example #15
Source File: forms.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def non_field_errors(self):
        """
        Returns an ErrorList of errors that aren't associated with a particular
        field -- i.e., from Form.clean(). Returns an empty ErrorList if there
        are none.
        """
        return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield')) 
Example #16
Source File: forms.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def non_field_errors(self):
        """
        Returns an ErrorList of errors that aren't associated with a particular
        field -- i.e., from Form.clean(). Returns an empty ErrorList if there
        are none.
        """
        return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield')) 
Example #17
Source File: forms.py    From python with Apache License 2.0 5 votes vote down vote up
def non_field_errors(self):
        """
        Returns an ErrorList of errors that aren't associated with a particular
        field -- i.e., from Form.clean(). Returns an empty ErrorList if there
        are none.
        """
        return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield')) 
Example #18
Source File: test_views.py    From django-service-objects with MIT License 5 votes vote down vote up
def test_form_valid_invalid_inputs_error(self, form_invalid, form_valid):
        request, _, _ = self.build_request('GET', {})
        form = MagicMock()

        view = InvalidInputsErrorView()
        view.request = request
        view.form_valid(form)

        form_valid.assert_not_called()
        form_invalid.assert_called_once_with(form)
        form.add_error.assert_has_calls([
            call(NON_FIELD_ERRORS, [non_field_error]),
            call('field1', [field1_error])
            ], any_order=True) 
Example #19
Source File: stream_block.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_form(self, value, prefix='', errors=None):
        error_dict = {}
        if errors:
            if len(errors) > 1:
                # We rely on StreamBlock.clean throwing a single
                # StreamBlockValidationError with a specially crafted 'params'
                # attribute that we can pull apart and distribute to the child
                # blocks
                raise TypeError('StreamBlock.render_form unexpectedly received multiple errors')
            error_dict = errors.as_data()[0].params

        # value can be None when the StreamField is in a formset
        if value is None:
            value = self.get_default()
        # drop any child values that are an unrecognised block type
        valid_children = [child for child in value if child.block_type in self.child_blocks]

        list_members_html = [
            self.render_list_member(child.block_type, child.value, "%s-%d" % (prefix, i), i,
                                    errors=error_dict.get(i), id=child.id)
            for (i, child) in enumerate(valid_children)
        ]

        return render_to_string('wagtailadmin/block_forms/stream.html', {
            'prefix': prefix,
            'help_text': getattr(self.meta, 'help_text', None),
            'list_members_html': list_members_html,
            'child_blocks': self.sorted_child_blocks(),
            'header_menu_prefix': '%s-before' % prefix,
            'block_errors': error_dict.get(NON_FIELD_ERRORS),
            'classname': getattr(self.meta, 'form_classname', None),
        }) 
Example #20
Source File: stream_block.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, block_errors=None, non_block_errors=None):
        params = {}
        if block_errors:
            params.update(block_errors)
        if non_block_errors:
            params[NON_FIELD_ERRORS] = non_block_errors
        super().__init__(
            'Validation error in StreamBlock', params=params) 
Example #21
Source File: forms.py    From bioforum with MIT License 5 votes vote down vote up
def non_field_errors(self):
        """
        Return an ErrorList of errors that aren't associated with a particular
        field -- i.e., from Form.clean(). Return an empty ErrorList if there
        are none.
        """
        return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield')) 
Example #22
Source File: forms.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def non_field_errors(self):
        """
        Return an ErrorList of errors that aren't associated with a particular
        field -- i.e., from Form.clean(). Return an empty ErrorList if there
        are none.
        """
        return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield')) 
Example #23
Source File: models.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def _update_errors(self, message_dict):
        for k, v in message_dict.items():
            if k != NON_FIELD_ERRORS:
                self._errors.setdefault(k, self.error_class()).extend(v)
                # Remove the data from the cleaned_data dict since it was invalid
                if k in self.cleaned_data:
                    del self.cleaned_data[k]
        if NON_FIELD_ERRORS in message_dict:
            messages = message_dict[NON_FIELD_ERRORS]
            self._errors.setdefault(NON_FIELD_ERRORS, self.error_class()).extend(messages) 
Example #24
Source File: forms.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_unique(self):
        '''This clean method will check for unique_together condition'''
        # Collect unique_checks and to run from all the forms.
        all_unique_checks = set()
        all_date_checks = set()
        forms_to_delete = self.deleted_forms
        valid_forms = [form for form in self.forms if form.is_valid() and form not in forms_to_delete]
        for form in valid_forms:
            unique_checks, date_checks = form.instance._get_unique_checks()
            all_unique_checks.update(unique_checks)
            all_date_checks.update(date_checks)

        errors = []
        # Do each of the unique checks (unique and unique_together)
        for uclass, unique_check in all_unique_checks:
            seen_data = set()
            for form in valid_forms:
                # Get the data for the set of fields that must be unique among the forms.
                row_data = (
                    field if field in self.unique_fields else form.cleaned_data[field]
                    for field in unique_check if field in form.cleaned_data
                )
                # Reduce Model instances to their primary key values
                row_data = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') else d
                                 for d in row_data)
                if row_data and None not in row_data:
                    # if we've already seen it then we have a uniqueness failure
                    if row_data in seen_data:
                        # poke error messages into the right places and mark
                        # the form as invalid
                        errors.append(self.get_unique_error_message(unique_check))
                        form._errors[NON_FIELD_ERRORS] = self.error_class([self.get_form_error()])
                        # remove the data from the cleaned_data dict since it was invalid
                        for field in unique_check:
                            if field in form.cleaned_data:
                                del form.cleaned_data[field]
                    # mark the data as seen
                    seen_data.add(row_data)

        if errors:
            raise ValidationError(errors) 
Example #25
Source File: verification.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        place = self.get_object()
        place_data = serializers.serialize('json', [place], fields=PlaceForm._meta.fields)
        place_data = json.loads(place_data)[0]['fields']
        owner_data = serializers.serialize('json', [place.owner], fields=ProfileForm._meta.fields)
        owner_data = json.loads(owner_data)[0]['fields']

        owner_form = ProfileForm(data=owner_data, instance=place.owner)
        place_form = PlaceForm(data=place_data, instance=place)

        data_correct = all([owner_form.is_valid(), place_form.is_valid()])  # We want both validations.
        viewresponse = {'result': data_correct}
        if not data_correct:
            viewresponse['err'] = OrderedDict()
            data_problems = set()
            for form in [owner_form, place_form]:
                viewresponse['err'].update({
                    str(form.fields[field_name].label) : list(field_errs)       # noqa: E203
                    for field_name, field_errs
                    in [(k, set(err for err in v if err)) for k, v in form.errors.items()]
                    if field_name != NON_FIELD_ERRORS and len(field_errs)
                })
                data_problems.update(form.errors.get(NON_FIELD_ERRORS, []))
            if len(data_problems):
                viewresponse['err'+NON_FIELD_ERRORS] = list(data_problems)
        else:
            place.set_check_status(self.request.user)

        if request.is_ajax():
            return JsonResponse(viewresponse)
        else:
            return TemplateResponse(
                request,
                self.template_names[data_correct],
                context={'view': self, 'place': place, 'result': viewresponse}
            ) 
Example #26
Source File: renderers.py    From drf-json-api with MIT License 4 votes vote down vote up
def wrap_error(
            self, data, renderer_context, keys_are_fields, issue_is_title):
        """Convert error native data to the JSON API Error format

        JSON API has a different format for errors, but Django REST Framework
        doesn't have a separate rendering path for errors.  This results in
        some guesswork to determine if data is an error, what kind, and how
        to handle it.

        As of August 2014, there is not a consensus about the error format in
        JSON API.  The format documentation defines an "errors" collection, and
        some possible fields for that collection, but without examples for
        common cases.  If and when consensus is reached, this format will
        probably change.
        """

        response = renderer_context.get("response", None)
        status_code = str(response and response.status_code)

        errors = []
        for field, issues in data.items():
            if isinstance(issues, six.string_types):
                issues = [issues]
            for issue in issues:
                error = self.dict_class()
                error["status"] = status_code

                if issue_is_title:
                    error["title"] = issue
                else:
                    error["detail"] = issue

                if keys_are_fields:
                    if field in ('non_field_errors', NON_FIELD_ERRORS):
                        error["path"] = '/-'
                    else:
                        error["path"] = '/' + field

                errors.append(error)
        wrapper = self.dict_class()
        wrapper["errors"] = errors
        return wrapper 
Example #27
Source File: forms.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def add_error(self, field, error):
        """
        Update the content of `self._errors`.

        The `field` argument is the name of the field to which the errors
        should be added. If its value is None the errors will be treated as
        NON_FIELD_ERRORS.

        The `error` argument can be a single error, a list of errors, or a
        dictionary that maps field names to lists of errors. What we define as
        an "error" can be either a simple string or an instance of
        ValidationError with its message attribute set and what we define as
        list or dictionary can be an actual `list` or `dict` or an instance
        of ValidationError with its `error_list` or `error_dict` attribute set.

        If `error` is a dictionary, the `field` argument *must* be None and
        errors will be added to the fields that correspond to the keys of the
        dictionary.
        """
        if not isinstance(error, ValidationError):
            # Normalize to ValidationError and let its constructor
            # do the hard work of making sense of the input.
            error = ValidationError(error)

        if hasattr(error, 'error_dict'):
            if field is not None:
                raise TypeError(
                    "The argument `field` must be `None` when the `error` "
                    "argument contains errors for multiple fields."
                )
            else:
                error = error.error_dict
        else:
            error = {field or NON_FIELD_ERRORS: error.error_list}

        for field, error_list in error.items():
            if field not in self.errors:
                if field != NON_FIELD_ERRORS and field not in self.fields:
                    raise ValueError(
                        "'%s' has no field named '%s'." % (self.__class__.__name__, field))
                if field == NON_FIELD_ERRORS:
                    self._errors[field] = self.error_class(error_class='nonfield')
                else:
                    self._errors[field] = self.error_class()
            self._errors[field].extend(error_list)
            if field in self.cleaned_data:
                del self.cleaned_data[field] 
Example #28
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_update_error_dict(self):
        class CodeForm(Form):
            code = CharField(max_length=10)

            def clean(self):
                try:
                    raise ValidationError({'code': [ValidationError('Code error 1.')]})
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                try:
                    raise ValidationError({'code': [ValidationError('Code error 2.')]})
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                try:
                    raise ValidationError({'code': forms.ErrorList(['Code error 3.'])})
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                try:
                    raise ValidationError('Non-field error 1.')
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                try:
                    raise ValidationError([ValidationError('Non-field error 2.')])
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                # The newly added list of errors is an instance of ErrorList.
                for field, error_list in self._errors.items():
                    if not isinstance(error_list, self.error_class):
                        self._errors[field] = self.error_class(error_list)

        form = CodeForm({'code': 'hello'})
        # Trigger validation.
        self.assertFalse(form.is_valid())

        # update_error_dict didn't lose track of the ErrorDict type.
        self.assertIsInstance(form._errors, forms.ErrorDict)

        self.assertEqual(dict(form.errors), {
            'code': ['Code error 1.', 'Code error 2.', 'Code error 3.'],
            NON_FIELD_ERRORS: ['Non-field error 1.', 'Non-field error 2.'],
        }) 
Example #29
Source File: forms.py    From bioforum with MIT License 4 votes vote down vote up
def add_error(self, field, error):
        """
        Update the content of `self._errors`.

        The `field` argument is the name of the field to which the errors
        should be added. If it's None, treat the errors as NON_FIELD_ERRORS.

        The `error` argument can be a single error, a list of errors, or a
        dictionary that maps field names to lists of errors. An "error" can be
        either a simple string or an instance of ValidationError with its
        message attribute set and a "list or dictionary" can be an actual
        `list` or `dict` or an instance of ValidationError with its
        `error_list` or `error_dict` attribute set.

        If `error` is a dictionary, the `field` argument *must* be None and
        errors will be added to the fields that correspond to the keys of the
        dictionary.
        """
        if not isinstance(error, ValidationError):
            # Normalize to ValidationError and let its constructor
            # do the hard work of making sense of the input.
            error = ValidationError(error)

        if hasattr(error, 'error_dict'):
            if field is not None:
                raise TypeError(
                    "The argument `field` must be `None` when the `error` "
                    "argument contains errors for multiple fields."
                )
            else:
                error = error.error_dict
        else:
            error = {field or NON_FIELD_ERRORS: error.error_list}

        for field, error_list in error.items():
            if field not in self.errors:
                if field != NON_FIELD_ERRORS and field not in self.fields:
                    raise ValueError(
                        "'%s' has no field named '%s'." % (self.__class__.__name__, field))
                if field == NON_FIELD_ERRORS:
                    self._errors[field] = self.error_class(error_class='nonfield')
                else:
                    self._errors[field] = self.error_class()
            self._errors[field].extend(error_list)
            if field in self.cleaned_data:
                del self.cleaned_data[field] 
Example #30
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_update_error_dict(self):
        class CodeForm(Form):
            code = CharField(max_length=10)

            def clean(self):
                try:
                    raise ValidationError({'code': [ValidationError('Code error 1.')]})
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                try:
                    raise ValidationError({'code': [ValidationError('Code error 2.')]})
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                try:
                    raise ValidationError({'code': forms.ErrorList(['Code error 3.'])})
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                try:
                    raise ValidationError('Non-field error 1.')
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                try:
                    raise ValidationError([ValidationError('Non-field error 2.')])
                except ValidationError as e:
                    self._errors = e.update_error_dict(self._errors)

                # The newly added list of errors is an instance of ErrorList.
                for field, error_list in self._errors.items():
                    if not isinstance(error_list, self.error_class):
                        self._errors[field] = self.error_class(error_list)

        form = CodeForm({'code': 'hello'})
        # Trigger validation.
        self.assertFalse(form.is_valid())

        # update_error_dict didn't lose track of the ErrorDict type.
        self.assertIsInstance(form._errors, forms.ErrorDict)

        self.assertEqual(dict(form.errors), {
            'code': ['Code error 1.', 'Code error 2.', 'Code error 3.'],
            NON_FIELD_ERRORS: ['Non-field error 1.', 'Non-field error 2.'],
        })