75
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.
7
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 %}
- [Django]-Django Error u"'polls" is not a registered namespace
- [Django]-Apache or Nginx to serve Django applications?
- [Django]-How to POST a django form with AJAX & jQuery
6
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.
- [Django]-ImportError: cannot import name '…' from partially initialized module '…' (most likely due to a circular import)
- [Django]-How to assign a local file to the FileField in Django?
- [Django]-List field in model?
4
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
- [Django]-Migrating from django user model to a custom user model
- [Django]-Circular dependency in Django Rest Framework serializers
- [Django]-How to show a many-to-many field with "list_display" in Django Admin?
Source:stackexchange.com