Django form error messages not showing

So, I have my opinion:

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 looked like this:

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

and if a problem occurs on the form (for example, if one of the fields was missing), it will automatically display an error message. After I separated the form fields in the template (made {{form.first_name}}, {{form.last_name}} and {{form.password}} my section), he automatically stopped reporting error messages. This is normal?

But the main problem is why my {{if form.errors}} statement is not working / not displaying error messages if there are error messages? For example, if I intentionally do not fill out a field on the form and click the "Submit" button, the database does not receive updates (which is good, but it does not give any error messages). Any idea why?

I also tried to remove {{forms.non_field_errors}} and tried to return only field errors as follows:

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

but it still doesn't work.

+4
source share
2 answers

I found a mistake (typo).

The fragment 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 .

+3
source

You should submit your form context again if is_valid () is not true,

  if form.is_valid(): return redirect('/user/contact/') else: return render(request, 'users/contact.html', context={'form': form}) 

because your errors will still appear in your form: it will return a ValueError

0
source

All Articles