4

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 %}

2 Answers 2

5

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 %}
Sign up to request clarification or add additional context in comments.

7 Comments

it worked but how can i ignore This field is required. error
@ChamsAgouni: by setting the required option to False in the form. Why would you ignore this in the template? It is the wrong place since not displaying the error, will not all of a sudden get the form validated.
because i would to do that by jquery
@ChamsAgouni, as Willem Van Onsem said, you can ignore what you want by setting required=False to the field wanted. It's not a good idea to let Jquery do this as a user can easily edit the form via Inspect Element in browsers. all the logic must go to the backend unless jquery will check the requirement before submitting the form, and in the top of that, Django will also check
how i can change This field is required to Username field is required
|
2

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 %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.