Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 570
Leaf Eyes Sdimh Avatar asked Jan 30 '15 16:01

Leaf Eyes Sdimh


People also ask

How do I get alert messages in Django?

To display alert messages in Django, (1) check that the settings are configured properly, (2) add a message to a view function, and (3) display the message in a template. INSTALLED_APPS = [ ... 'django. contrib. messages', ... ]


2 Answers

There are many ways to do this well (see "flash" in Bootstrap, for example)... but here's how you do literally what you ask about.

In the view you redirect to, pass a message value to your template:

return render_to_response('template_name', message='Save complete')

And in your template, add this script:

<script>
    alert('{{ message }}');
</script>
like image 123
dylrei Avatar answered Oct 16 '22 07:10

dylrei


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).

like image 36
Alex T Avatar answered Oct 16 '22 07:10

Alex T