Reputation: 3376
In the Django Documentation, the suggested way to validate fields that depend on each other is in the form's clean()
method. It makes sense, but the problem I'm dealing with is how to notify the view what fields are causing problems.
When it's just one field who is failing, I can check it like this:
for field in form:
if field.errors:
# I know exactly in what field is the problem
But if the error comes from the clean()
method, all I got is the error message:
if form.errors:
for error in form.errors:
# I know there's a problem, and I got an error message,
# but I don't know what are the fields that cause it.
Think in the typical registration form, where you must write twice the email and twice the password to avoid typos. By example, I want to change the CSS class of the two password fields if they have different values, but in the view, I've got no reference to the widget causing the problem. The only information I have is the error message thrown by the ValidationError in the Form's clean()
method. How do I know if the problem is with the password fields or with the email fields? And I guess that parsing that error message is not the way to go.
Upvotes: 2
Views: 133
Reputation: 22469
You can add a field level error like this:
self._errors["<field_name>"] = self.error_class([msg])
If you raise a ValidationError
in clean
, it will result in a non field error. See the bottom snippet at the documentation page.
Upvotes: 3