How to handle Django form errors not in UL?

Errors in my form Django is rendering in UL according to docs ...

Django

{{ form.non_field_errors }} 

HTML

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

How can I visualize errors so that they are not displayed in UL, but in the paragraph tag for each corresponding error? Therefore, itโ€™s ideal ...

 <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 }} 
+49
django django-forms
Sep 14 '11 at 16:14
source share
2 answers

You can display your error in the template as follows:

 <p>{{ form.fieldname.errors.as_text }}</p> 
+94
Sep 15 '11 at 3:00
source share

It clearly cannot display fields in the context, because these are โ€œnon-field errors,โ€ as the name of the attribute implies. The only way to fix this is to add the error in the right place when checking. For example, doing the following results with borderless 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 so that this error appears in 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 call the HTML code required to display the form widget. Using {{form.name_of_field.errors}} displays a list of form errors displayed as an unordered list. It might look like this:

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

There is a CSS error class in the list that allows you to appear. If you want to further customize the display of errors, you can do this by going through them (my attention):

 {% if form.subject.errors %} <ol> {% for error in form.subject.errors %} <li><strong>{{ error|escape }}</strong></li> {% endfor %} </ol> {% endif %} 
+12
Sep 14 '11 at 16:45
source share



All Articles