Reputation: 4668
In my home page I have a login form and sign up form, and i use the form.is_valid() to validate the form,
but instead of
return render(request,'registration/login.html', {'form': form})
I use
messages.error(request, 'username or password wrong.')
return redirect('/')
am doing this because in
return render(request,'registration/login.html', {'form': form})
after the form.is_valid() fail, refresh the page will cause a pop out box says resubmit confirm,I dont want this,so am using the second method.
the problem is that there is two form: login and signup , I can't put the error message in one place,that will be misleading ,so how to display two message in one page?
Upvotes: 2
Views: 5417
Reputation: 53386
You can use extra_tags
for message from messages framework to identify two different messages.
For example, for login errors
messages.error(request, 'username or password wrong.', extra_tags='login')
for sign up errors,
messages.error(request, 'username or password wrong.', extra_tags='signup')
And then in template depending upon tag you put message in appropriate form
{# login form #}
{%for message in messages %}
{%if "login" in message.tags %}
<p> {{message}} </p> {# show login error message #}
{%endif%}
{%endfor%}
{# signup form #}
{%for message in messages %}
{%if "signup" in message.tags %}
<p> {{message}} </p> {# show signup error message #}
{%endif%}
{%endfor%}
More reference at Adding extra message tags
Upvotes: 9
Reputation: 1517
you can use the form.errors dict, he stores the field name and his error messages, in case of an invalid form, like:
>>> print form.errors
{'password': [u'This field is required']}
and then you can use in your templates:
{% if 'username' in form.errors.keys %}
<div class="error-message">
Your username input error message!
</div>
{% endif %}
{% if 'password' in form.errors.keys %}
<div class="error-message">
Your password input error message!
</div>
{% endif %}
The only problem that i can see, is the output message, she is a bit ugly =] But you can use another tricks to make this more pretty, like using other dicts to store the pretty message and get him by the field name... you make this choice.
*sorry for my bad english ;/
Upvotes: 0