Search code examples
djangodjango-formsdjango-templatesdjango-errors

Control the form errors display while using {{ form.as_ul }} in Django templates.


I like the convenient output form method {{ form.as_ul }} but is there a way I can still continue to use it but capture all the errors upfront instead of displaying the error just above each field.

I understand that there are ways to loop through each form element and so on as mentioned in django docs but I want to continue to utilize the capability of form.as_ul() except get control over error display.


Solution

  • Solved this problem by using Reusable Form Templates.

    Its simple...

    1. Create a reusable template with the following code snippets based on your need.

    2. If you want to display all errors right at the top of the form...

      {% if form %}
          {% if form.errors %}
               {% for field in form %}
                    {{field.errors}}
               {% endfor %}
          {% endif %}
          {% for field in form %}
               <li>{{ field.label_tag }}: {{ field }}</li>
          {% endfor %}
      {% endif %}
      
    3. If you want to display all errors right after each form field without the default html elements around error use...

      {% for field in form %}
          {{ field.label_tag }}: {{ field }}
          {% for error in field.errors %}{{ error }}{% endfor %}
      {% endfor %}
      
    4. Used the second template and created a Inclusion Tag