consider this form:
class LoginForm(forms.Form):
email = forms.EmailField(label="Email", required = True)
password = forms.CharField(label="Password", widget=forms.PasswordInput(), required=True)
When I validate the form, i want just one error method to be used: 'invalid email and/or password' and this no matter whether it was not an email field, any of the field is blank, or the combination of password/email is incorrect.
After research, I believe (unless I am wrong) that I need to use run_validators()
(from django docs": "aggregates all the errors into a single ValidationError")
开发者_JAVA技巧However I am confused on how I should define this.
The run_validators
method you pointed to is a per field method, so doesn't really solve your problem. It aggregates multiple per-field validators like "field can't be empty", "is not an email address", etc to pull out the first failed validator.
If you want any error to show that message, I would just deal with it in the template.
You could rephrase your requirements as "if the form is invalid, display one error message", otherwise, successfully log in.
{% if form.errors %}
invalid email and/or password
{% endif %}
I don't see a reason why you'd want to modify your form for the same ultimate effect, but I suppose that's no fun.
If you want per field errors for whatever reason, here's a solution I've come up with to overwrite all errors.
def clean(self):
for key, value in self._errors.iteritems():
self._errors[key] = self.error_class(['invalid email and/or password'])
return self.cleaned_data
This would take care of non field errors as well, as those are in the same dict.
精彩评论