Django How to implement alert()(popup message) after complete method in view

Leaf Eyes Sdimh picture Leaf Eyes Sdimh · Jan 30, 2015 · Viewed 59.1k times · Source

I would like to have an alert() message (like in javascript) after method in view.py is complete

My method is

def change_password(request):
    dictData = getInitialVariable(request)

    in_username = request.POST['txt_username']
    in_password = request.POST['txt_password']
    in_new_password = request.POST['txt_new_password']


    user = authenticate(username=in_username, password=in_password)
    if user is not None:
        if user.is_active:
            u = User.objects.get(username=in_username)
            u.set_password(in_new_password)
            u.save()

            # Redirect to a success page.
            return HttpResponseRedirect('/profiles/'+in_username)

After u is saved to database, the popup message will be shown. How could I implement it?

Answer

Alex T picture Alex T · Feb 4, 2017

I think the best solution would be messages (docs)

As described in message levels docs Django suggests to use "INFO" level messages to communicate with users.

By default messages are enabled in Django. If my example doesn't work for you as it is you should check enable messages block

View part:

from django.contrib import messages

def change_password(request):
   ...your stuff...

   messages.info(request, 'Your password has been changed successfully!')
   return HttpResponseRedirect('/profiles/'+in_username)

Template part:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

You can paste massage output in specific view or in general templates (layout/header).