django form error messages not showing

SilentDev picture SilentDev · Sep 22, 2013 · Viewed 19.3k times · Source

So I have my view:

def home_page(request):
    form = UsersForm()
    if request.method == "POST":
        form = UsersForm(request.POST)

        if form.is_valid():
            form.save()
    c = {}
    c.update(csrf(request))
    c.update({'form':form})
    return render_to_response('home_page.html', c)

my forms.py:

class UsersForm(forms.ModelForm):

    class Meta:
        model = Users
        widgets = {'password':forms.PasswordInput()}

    def __init__(self, *args, **kwargs):
        super( UsersForm, self ).__init__(*args, **kwargs)
        self.fields[ 'first_name' ].widget.attrs[ 'placeholder' ]="First Name"  
        self.fields[ 'last_name' ].widget.attrs[ 'placeholder' ]="Last Name"
        self.fields[ 'password' ].widget.attrs[ 'placeholder' ]="Password"

and my template:

<html>
    <body>

    <form method="post" action="">{% csrf_token %}
        {{ form.first_name }} {{form.last_name }} <br>
        {{ form.password }} <br>
        <input type="submit" value="Submit Form"/>
    </form>

    {% if form.errors %}
        {% for field in form %}
        {% for error in field.errors %}
            <p> {{ errors }} </p>
        {% endfor %}
        {% endfor %}
        {% for error in form.non_field_errors %}
        <p> {{ error }} </p>
        {% endfor %}
    {% endif %}

    </body>
</html>

Now, keep in mind that before I split the form field, my form just looked like this:

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

and if the form had a problem (like if one of the fields was missing) it would automatically give an error message. After I split up the form fields in the template (made {{ form.first_name }}, {{ form.last_name }} and {{ form.password }} their own section) it stopped automatically giving error messages. Is this normal?

But the main problem is, how come my {{ if form.errors }} statement is not working / displaying error messages if there are error messages? For example, if I purposely not fill out a field in the form and I click submit, the database does not get updates (which is a good thing) but it does not give any error messages. Any idea why?

I also tried remove the {{ forms.non_field_errors }} and tried to return just field errors like so:

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

but it still doesn't work.

Answer

SilentDev picture SilentDev · Sep 23, 2013

I found the mistake (typo).

The snippet should be:

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

I had errors instead of error.