Bubai
Bubai

Reputation: 1240

problem with setting & accessing a variable value in django template

I want to set a variable err for errors in the form fields (using django 2.1.3):

{% for field in form %}
    {% if field.errors %}
        {% with field.errors as err %}{% endwith %}
    {% endif %}
{% endfor %}


{% if err %}
    <div class="alert alert-danger fade show">
        <button type="button" class="close" data-dismiss="alert"
           aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        {{ err }}
    </div>
{% endif %}

But, while rendering to html the value of the variable has no output. Though, there are errors, which I've raised using forms.ValidationError.

Also, try this like ...

{% for field in form %}
    {% if field.errors %}
        <div ... >
            ...
            ...
            {{ field.errors }}
        </div>
    {% endif %}
{% endfor %}

In this case, output or the errors are showing, but with multiple <div> elements & n no. of times.
I know that, it can be done by another way in the views.py: using 'django.contrib.messages'. Then sending errors to messages.error(), inside form.is_valid(), then ...

{% if messages %}
    {% for message in messages %}
        {{ message }}
    {% endfor %}
{% endif %}

But, I want to manipulate it from forms.py file. So, how do I do it? ๐Ÿ™„๏ธ๐Ÿ˜•๏ธ๐Ÿค”๏ธ๐Ÿคจ๏ธ
Thanks in advance!!

Upvotes: 0

Views: 116

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

The scope of a with statement is until the matching endwith. Your endwidth is immediately after the with, so the variable exists for no time at all.

Even if this worked, you only define a single err anyway; if there are multiple errors it would only have the value of the last one, which defeats the whole purpose of what you are trying to do.

You should not use contrib.messages for this. You should use the errors from the form, not from the field.

{% if form.errors %}
    <div ... >
        ...
        ...
        {% for error in form.errors %}
        {{ error }}
        {% endfor %}
    </div>
{% endif %}

Note you can further customise the way errors are displayed by defining an ErrorList subclass.

Upvotes: 1

Related Questions