[Fixed]-Django How to implement alert()(popup message) after complete method in view

28👍

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

👤Alex T

15👍

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>
👤dylrei

5👍

add the messages.success after the send_mail()

from django.contrib import messages

def contact(request):

subject = request.POST['name']

message = request.POST['message']

recipient = settings.EMAIL_HOST_USER

recipient = [recipient,]

email_from = request.POST['mailing']

send_mail( subject, message, email_from, recipient )

messages.success(request, 'Successfully Sent The Message!')

return redirect('send_email')  

add this code in your templates in body

    {% if messages %}
        {% for message in messages %}
         {% if message.tags %}  <script>alert("{{ message }}")</script> {% endif %}

        {% endfor %}

    {% endif %}

-4👍

Simply redirect to /profiles/in_username/password_updated instead

you could use a HTML template on /profiles/in_username/password_updated:

This template redefines the one used in /profiles/in_username and add a javascript with alert

<!DOCTYPE html>
<html lang="en">
<body>
<script>
alert("Your message");
</script>
[...]
</body>
</html>

Simply use render_to_response in that view:

from django.shortcuts import render_to_response
return render_to_response('mytemplate.html', {"in_username": in_username});

See https://docs.djangoproject.com/en/1.7/topics/templates/ for more info on templating.

Leave a comment