Reputation: 185
I saw this post: How to raise multiple ValidationError on Django?
However I have some questions. In the accepted answer, andilabs writes:
raise ValidationError({
'field_name_1': ["Field not allowed to change"],
'field_name_2': ["Field not allowed to change"],
})
Do the values have to be in a List even though it is just one string? If so, anyone know why? Or where in the documentation it says so? I have not found it in https://docs.djangoproject.com/en/3.0/ref/forms/validation/#raising-multiple-errors.
The below code works for me and in my html template I can do {{ form.user.errors }} to have it show up in a div on submission. For who wants to know what context I am using it in, I am using it in a Form view, and inside it I have a def clean(self) method, where I override the parent clean(). Some code for reference:
class RegisterForm(forms.Form):
user = forms.CharField()
**the fields and stuff**
def clean(self):
error = {}
cleaned = super().clean()
if 'user' not in cleaned_data:
error['user'] = ['Username is empty']
**check if other fields are not there, check password length minimum, etc.**
if len(error) != 0:
raise ValidationError(error)
return cleaned
Upvotes: 0
Views: 1466
Reputation: 820
From the Doctring of the __init__
method for ValidationError
in django.core.exceptions
:
"""
The `message` 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.
"""
Upvotes: 1