Login

Nice form errors

Author:
SmileyChris
Posted:
October 18, 2009
Language:
Python
Version:
1.1
Score:
7 (after 7 ratings)

Nicely output all form errors in one block, using field labels rather than the field attribute names.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django import template
from django import forms
from django.forms.forms import NON_FIELD_ERRORS
from django.forms.util import ErrorDict


register = template.Library()


@register.filter
def nice_errors(form, non_field_msg='General form errors'):
    nice_errors = ErrorDict()
    if isinstance(form, forms.BaseForm):
        for field, errors in form.errors.items():
            if field == NON_FIELD_ERRORS:
                key = non_field_msg
            else:
                key = form.fields[field].label
            nice_errors[key] = errors
    return nice_errors

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

whiteinge (on October 18, 2009):

Example?

#

daemian_mack (on July 10, 2010):

Example:

(My line-formatting is going to get wiped out by the Markdown processor, so you'll have to paste this into an editor and do indenting there.)

` {% if form.errors %}<br /> <br />

    {% with form|nice_errors as qq %} {% for error_name,desc in qq.items %}
  • {{ error_name }}:
  • {{ desc }}
  • {% endfor %}

{% endwith %}<br /> {% endif %} <br /> `

Since ErrorDict does some auto-HTMLizing of the dict values, this will produce doubly-nested unordered lists.

#

Please login first before commenting.