61

The errors in my Django form are rendering in a UL as per the docs...

Django

{{ form.non_field_errors }}

HTML

<ul class="errorlist">
  <li>Sender is required.</li>
</ul>

How can I render the errors so they appear not in a UL, but in a paragraph tag for each fields relevant error? So ideally...

<ul>
  <li>
    <label>...</label>
    <input>...</input>
    <p>Error message...</p>
  </li>
</ul>

EDIT:

I should have used this code in my example for clarity...

{{ form.fieldname.errors }}

2 Answers 2

110

You can display your error as the following in your template:

<p>{{ form.fieldname.errors.as_text }}</p>
1
  • 4
    Thanks for your clue. But I think your code worked on individual field, how if I used generated form.as_p?? so I could not put on each fields Commented Aug 17, 2014 at 4:14
16

It obviously can't render within the context of the field because these are "non-field errors" as the attribute name implies. The only way to fix this is to add the error in the right place when validating. For example, doing the following results in non-field errors:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def clean(self):
        somefield = self.cleaned_data.get('somefield')
        if not somefield:
            raise forms.ValidationError('Some field is blank')

However, you can do the following to make that error still show on the right field:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def clean(self):
        somefield = self.cleaned_data.get('somefield')
        if not somefield:
            if not self._errors.has_key('somefield'):
                from django.forms.util import ErrorList
                self._errors['somefield'] = ErrorList()
            self._errors['somefield'].append('Some field is blank')

UPDATE:

From the Django docs:

Each named form-field can be output to the template using {{ form.name_of_field }}, which will produce the HTML needed to display the form widget. Using {{ form.name_of_field.errors }} displays a list of form errors, rendered as an unordered list. This might look like:

<ul class="errorlist">
    <li>Sender is required.</li>
</ul>

The list has a CSS class of errorlist to allow you to style its appearance. If you wish to further customize the display of errors you can do so by looping over them (emphasis mine):

{% if form.subject.errors %}
    <ol>
    {% for error in form.subject.errors %}
        <li><strong>{{ error|escape }}</strong></li>
    {% endfor %}
    </ol>
{% endif %}
1
  • 1
    Sorry, I wasn't clear, if I process '{{ form.fieldname.errors }}' it will still dump the error messages in a UL. I've edited my question to reflect this.
    – Dan
    Commented Sep 14, 2011 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.