Question

So suppose I have a form called form and I want to display on the screen only the first error message, if there exists error messages. I did some research and apparently you can access just the first error message by typing this in the template.

{{ form.errors.0 }}

but it doesn't seem to work for me, it doesn't display anything. How do I make my template so that it displays just the first error message if there are form errors? Here is what I tried.

<html>
    <body>

    <form method="post" action="">{% csrf_token %}
        {{ form }}
    <input type="submit" value="Register"/>
    </form>

    {% if form.errors %}
            {{ form.errors.0 }}
        {% endif %}
    </body>
</html>

So, what I want is, I want to display only the first error in {{form.errors}}. Note that when I change

{{ form.errors.0 }}

to

{{ form.errors }}

it does display all of the errors, however, I only want to display one error, just the First error message. So, any idea why my dot notation isn't working?

Was it helpful?

Solution

The form.errors is not a dictionary, at least according to other related questions in StackOverflow:

django accessing errors

django: how to access only first error message in form.errors?

If you really need to get only first error (remembering that all field errors will come together), you can try to convert to values and then get the first item, like:

{{form.errors.values.0}}

or

{{form.errors.items.0}}

This second will return a tuple with label and error message.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top