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?
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', ... ]
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>
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With