Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of errors in a Django form

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.

like image 828
icktoofay Avatar asked Jan 09 '10 22:01

icktoofay


People also ask

How do I show errors in Django?

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.

How do I display validation error in Django?

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.

What is form Is_valid () in Django?

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.

What is Django cleaned_data?

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).


2 Answers

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.

like image 143
Danny Roberts Avatar answered Sep 20 '22 09:09

Danny Roberts


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 %} 
like image 42
sandes Avatar answered Sep 21 '22 09:09

sandes