Categories
Python Answers

How to show form with error message if not valid with Python Django Forms?

Spread the love

To show form with error message if not valid with Python Django Forms, we can use form.errors to check for errors.

For instance, we write

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

to use form.errors in the if block to check for errors.

If there’re any errors, then we loop through the form errors and render the field.errors with a for loop.

And we render non-field errors by looping through form.non_field_errors with another for loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *