Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Display One form error in Django

Tags:

python

django

I have this in my template and i want only to display username error not all form errors

{% for field in form %}
    {% for error in field.errors %}
        <div class="row">
            <div class="small-12 columns val-error-msg error margin-below">
                {{ error }}
            </div>
        </div>
    {% endfor %}
{% endfor %}
like image 262
Chams Agouni Avatar asked Sep 05 '25 16:09

Chams Agouni


2 Answers

You could specify a field error with form.field_name.errors

like:

{% if form.username.errors %}
    {{form.username.errors}}
    # or
    # {{form.username.errors.as_text}}
    # this will remove the `<ul></ul>` tag that django generates by default
{% endif %}
like image 146
Lemayzeur Avatar answered Sep 07 '25 14:09

Lemayzeur


Ever field has .errors attached to it as well. But note that each field can contain multiple errors (for example a password can be too short, and contain illegal symbols).

You can access these errors through {{ form.field.errors }}, but you already obtain such elements. In case you want to filter in the template to only show the errors of - for example - the username field, you can do so with an {% if ... %} statement:

{% for field in form %}
    {% if field.name == "username" %}
    {% for error in field.errors %}
        <div class="row">
            <div class="small-12 columns val-error-msg error margin-below">
                {{ error }}
            </div>
        </div>
    {% endfor %}
    {% endif %}
{% endfor %}
like image 21
Willem Van Onsem Avatar answered Sep 07 '25 14:09

Willem Van Onsem