displaying django form error messages instead of just the field name

拟墨画扇 提交于 2019-12-22 13:05:55

问题


I have a form and I want to display the errors in a for loop.

{% for error in form.errors %}
    <tr><td>{{ error }}</td></tr>
{% endfor %}

By doing this the {{ error }} only contains the field name that has an error, but not the error message. How can I display the error message?


回答1:


You can get all field errors in a form like this:

{% for field in form %}
  {{ field.errors|striptags }}
{% endfor %}

Or for a specific field:

{% if form.subject.errors %}
    <ol>
    {% for error in form.subject.errors %}
        <li><strong>{{ error|escape }}</strong></li>
    {% endfor %}
    </ol>
{% endif %}

More Infos here: https://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template



来源:https://stackoverflow.com/questions/7585606/displaying-django-form-error-messages-instead-of-just-the-field-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!