Create pop up message in django - python

I am doing some calculations in my views.py and I want to show the result.
I have tried to use the following:
return render(request, index.html{message:variable})
and
return HttpResponse(message)
I want to show the result as a Popup message. How can I implement this?

first you have to render template by
return render_template( "example.html",message = any_variable)
and then you can show pop up on html via java script by
<script>
alert("This is alert box!"); // display string message
alert( {{message}} ); // display python variable
</script>
although i recommend using jinja as template

You can use Django messages https://docs.djangoproject.com/en/3.2/ref/contrib/messages/
from django.contrib import messages
messages.success(request, 'Success')
In your template, use something like:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

Related

Error message not working as expected in Django

I am trying to display a message on order creation success or failure. For messages.success(request, "My message") it is working as expected. But for messages.error(request, "My message") it is not as expected. I read the django messages framework docs, but no use. Can someone tell me why is this happening
Success Message:
Failed Message:
This is supposed to be red alert if I am not wrong.
Here's my html file.
base.html
<main role="main" class="container" >
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
views.py
if verify:
if response_dict['RESPCODE'] == '01':
messages.success(
request, "Thank you for ordering! Your items will be delivered soon")
return redirect(reverse('update-records', kwargs={'order_id': order_id}))
else:
messages.error(
request, "Your order could not be placed, here are the details: " + response_dict['RESPMSG'])
return redirect(reverse('profile-page'))
If the problem is alert-error not working you can use this after have the import statement of your message :
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.ERROR: 'danger'
}
Reference ->
https://docs.djangoproject.com/en/3.0/ref/contrib/messages/#message-tags
#Sowjanya R Bhat
The method you suggest can be hardcoded but I need to know, why isn't it implementing red alert my default. Your suggestion works however
<main role="main" class="container" >
{% if messages %}
{% for message in messages %}
{% if message.tags == "error"%}
<div class="alert alert-danger">
{{ message }}
</div>
{% else %}
<div class="alert alert-success">
{{ message }}
</div>
{% endif %}
{% endfor %}
{% endif %}
In your HTML:
<script>
setTimeout(function () {
$('#flash').fadeOut('fast');
},5000);
</script>
<div id="flash">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags}} m-0" role="alert">
<strong>{{ message }}</strong>
</div>
{% endfor %}
{% endif %}
</div>
in django settings.py:
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.ERROR: 'danger'
}
in django views:
from django.contrib import messages
if verify:
if response_dict['RESPCODE'] == '01':
messages.success(
request, "Thank you for ordering! Your items will be delivered soon")
return redirect(reverse('update-records', kwargs={'order_id': order_id}))
else:
messages.error(
request, "Your order could not be placed, here are the details: " + response_dict['RESPMSG'])
return redirect(reverse('profile-page'))
just use messages.warning instead, it would at least show a color.
This is because alert-error is not a bootstrap class.
The according class is named alert-danger.
Generally the tags line up nicely between bootstrap and django, this is why your code works. But as you see "error" != "danger".
To fix the issue replace
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
with
{% if message.tags == "error" %}
<div class="alert alert-danger">
{{ message }}
</div>
{% else %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endif %}

How to flash success and danger with different messages in flask.

I have a flask application where I want to flash different alert messages depending on an action.
here is my first message, where i check if an email matches my regex pattern:
reciver = str(email)
if not re.match(r"[^#]+#[^#]+\.[^#]+", reciver):
flash("Please enter a valid email address", 'error')
return render_template("about.html")
here is the second message, which is displayed if a message is sent successfully:
flash('Message sent succesfully', 'succes')
return render_template("about.html")
here is my HTML code:
<h1 class="mb-5"> Enter your message, and i will get back to you as soon as possible</h1>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success">
<li>{{ message }} </li>
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block body %}{% endblock %}
how can I make an alert-danger for the first message and an alert-success for the second message, is there some sort of conditional that can be used?
You can use the following pattern to specify the category parameter of the flash function.
:param category: the category for the message. The following values
are recommended: 'message' for any kind of message,
'error' for errors, 'info' for information
messages and 'warning' for warnings. However any
kind of string can be used as category.
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert {{ category }}"> {{ message|capitalize }} </div>
{% endfor %}
{% endif %}
{% endwith %}
By putting category in the class attribute, you can associate special colors with some css rules like :
.alert.success {
background-color: green;
}
.alert.error {
background-color: red;
}
flash('Message sent successfully', 'success')
flash("Please enter a valid email address", 'error')
These calls will generate:
<div class="alert success"> Message sent successfully </div>
<div class="alert error"> Please enter a valid email address </div>
Official documentation : http://flask.pocoo.org/docs/1.0/patterns/flashing/#flashing-with-categories
With flask 1.0.2 this similar but slightly different approach worked for me - slightly simpler I think:
flash('This is an error message in red', 'danger')
flash('This is an informational message in blue', 'info')
In Flask HTML template:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}" role="alert"> {{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
This way I didn't need to define any CSS and just used what was already in the default Flask distribution.

How to send message to HttpResponseRedirect in Django

I have added a middleware to a session-out user with my logic. I am trying to redirect to login page with a message. I am using HttpResponseRedirect(reverse('user_login')) for redirecting to my custom login page.
So, how to pass values to a page?
You can use django's messages framework. https://docs.djangoproject.com/en/stable/ref/contrib/messages/
In your views do:
from django.contrib import messages
messages.success(request, 'This is my message.')
And in your base template keep this piece of code.
{% if messages %}<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}</ul>{% endif %}
Or if don't want to use messages you can pass in the url.
from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('user_login') + '?autologout=true')
And in your template
{% if request.GET.autologout %}
<p>This is my message.</p>
{% endif %}

How to use toastr in Django for success or fail message

I have been using Django message framework to show the success or failure message in my application. But I want the UI to be good so I found out that toastr is a good way to display messages to the user. But I am not sure how to use it. Please guide me through this.
The function below saves the user to the database and when the user info is save a message is displayed:
def addSubscriber(request):
template = 'addSubscriber.html'
if request.method == 'POST':
form = addSubsForm(request.POST)
if form.is_valid():
f = form.save(commit=False)
f.save()
messages.success(request, "The Subscriber has been successfully added")
return redirect('report')
else:
messages.error(request, "Sorry the data has not been entered to the database")
else:
form = addSubsForm()
return render(request, template, {'form': form})
The following template shows the display of the message:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
Thanks for this question I was able to implement toastr with python, this is a more complete answer that was given by Neeraj Kumar.
In my case, It is much better than materialize, because that CSS kit disrupts my own CSS code and I don't have the time to do CSS debugging.
First, in your template, you have to set the JS files, example:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="{% static 'css/toastr.css' %}" media="all">
<script type="text/javascript" src="{% static 'js/toastr.min.js' %}"></script>
Next, inside of the body, you might put the options for the Toast messages (These options can be easily created in the Toastr demo page.
Finally, insert this code of block if you are using the standard tags of the messages framework from django:
{% if messages %}
{% for message in messages %}
{% if message.tags == 'success'%}
<script type=text/javascript>toastr.{{ message.tags }}('{{ message }}')</script>
{% elif message.tags == 'info' %}
<script type=text/javascript>toastr.{{ message.tags }}('{{ message }}')</script>
{% elif message.tags == 'warning' %}
<script type=text/javascript>toastr.{{ message.tags }}('{{ message }}')</script>
{% elif message.tags == 'error' %}
<script type=text/javascript>toastr.{{ message.tags }}('{{ message }}')</script>
{% endif %}
{% endfor %}
{% endif %}
I hope this can be helpful and time saving for other people.
Add toastr js and css in html code then write below code for showing toastr messages
{% for message in messages %}
toastr.{{ message.tags }}("{{ message }}");
{% endfor %}

Django checking for a query string

When someone clicks on my site's logout link, I want them to be redirected to the login page but I want a message to pop up saying that they were successfully logged out. However, I don't want this behaviour to occur when someone normally visits the login page.
I decided to pass in a query string so now when someone hits logout they are redirected to users/login/?logout. How can I check for this in my template though? I want to do something like:
{% if ______ %}
*Message box appears*
{% endif %}
Thanks!
Well, you can simply use the built-in Django messaging feature!
Here's a simple example:
# views.py
from django.contrib import messages
def register(request):
# Logic
# ...
messages.success(request, 'Registered successfully!')
# ...
# More logic
-
# example.html
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li class="{{ message.tags }}">
{{ message|safe }}
X
</li>
{% endfor %}
</ul>
{% endif %}
There's a more in-depth documentation available on Django's official docs website: https://docs.djangoproject.com/en/1.11/ref/contrib/messages/
Referring to this document, I believe what you are looking for is this
{% if not request.user.is_authenticated %}
<p>You are logged out!</p>
{% endif %}

Categories

Resources