You may want to access to "global" errors in your template, typically when you have a custom clean()
method which checks several fields. {{ form.errors }}
gives an < ul >, which is often not what you want, and {{ form.errors|join:", " }}
iterates in the keys of errors
(which are the names of fields, uninteresting).
The global errors
's key is "all", and Django doesn't allow us to do {{ form.errors.__all__ }}
.
This method returns an array, like a classic {{ form.field.errors }}
, and can be used with a join : {{ form.get_global_errors|join:", " }}
.
1 2 3 4 5 | class MyForm(forms.Form):
def get_global_errors(self):
errors = dict(self.errors)
return list(errors.get("__all__", []))
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
def get_global_errors(self): return self.errors and self.errors.get('_all_',[])
#
I am not sure about the situation at the time of writing this post, but global errors can be accessed by
{{ form.non_field_errors }}
#
Please login first before commenting.