Getting a list of errors in a Django form

前端 未结 4 1395
失恋的感觉
失恋的感觉 2020-12-13 13:39

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 loopin

相关标签:
4条回答
  • 2020-12-13 14:00

    You can use this code:

    {% if form.errors %}
        {% for field in form %}
            {% for error in field.errors %}
                <div class="alert alert-danger">
                    <strong>{{ error|escape }}</strong>
                </div>
            {% endfor %}
        {% endfor %}
    
        {% for error in form.non_field_errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    
    {% endif %}
    

    this add https://docs.djangoproject.com/en/3.0/ref/forms/api/#django.forms.Form.non_field_error

    0 讨论(0)
  • 2020-12-13 14:07

    If you want something simple with a condition take this way :

    {% if form.errors %}
      <ul>
        {% for error in form.errors %} 
          <li>{{ error }}</li>
        {% endfor %}
      </ul>
    {% endif %}  
    

    If you want more info and see the name and the error of the field, do this:

    {% if form.errors %}
      <ul>
        {% for key,value in form.errors.items %} 
          <li>{{ key|escape }} : {{ value|escape }}</li>
        {% endfor %}
      </ul>
    {% endif %}
    

    If you want to understant form.errors is a big dictionary.

    0 讨论(0)
  • 2020-12-13 14:10

    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 %}
    
    0 讨论(0)
  • 2020-12-13 14:16

    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.

    0 讨论(0)
提交回复
热议问题