I'm trying to create a form in Django. That works and all, but I want all the errors to be at the top of the form, not next to each field that has the error. I tried looping over form.errors, but it only showed the name of the field that had an error, not an error message such as "Name is required."
This is pretty much what I'd like to be able to use at the top of the form:
{% if form.??? %} <ul class="errorlist"> {% for error in form.??? %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %}
What would I use for ???
there? It's not errors
; that just outputs the names of the fields.
The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. For example, here is the default error message: >>> from django import forms >>> generic = forms.
To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).
form.errors is a dictionary. When you do {% for error in form.errors %}
error corresponds to the key.
Instead try
{% for field, errors in form.errors.items %} {% for error in errors %} ...
Etc.
Dannys's answer is not a good idea. You could get a ValueError.
{% if form.errors %} {% for field in form %} {% for error in field.errors %} {{field.label}}: {{ error|escape }} {% endfor %} {% endfor %} {% endif %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With