简体   繁体   中英

How to display multiple django messages in one page?

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?

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

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 ;/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM