Is there any way to save success message in context in django - python

I created a model form.Is it possible to add some message in context in views.py ?
Actually i want to display a success message in template page when form is submitted and data added in database.
for example i want to do this:
if form.save:
msg = 'Data inserted successfully'
context = {'msg': msg,}
I want to save success message in my context so therefore i will show in my template page

For showing the message after model save, you can follow this Stack Over Flow Question - Django: customizing the message after a successful form save
Please this messages functionality given by django framework for onetime messages. This is the second answer provided for the above question. There are a lot of ways mentioned in the documentation that could be implemented.
Simplest one is -
In Views.py:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Data inserted successfully.')
In template:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

Related

How can you output something when login is completed? Django allauth

I'm trying to build a form that when the login button is clicked, it displays a login succesful message. Here is the thing, I want that when the "login" button is clicked, the user gets redirected and in the redirected page (which is the home page), it should show the message. How can you do this in Django allauth with their default themes?
I've tried doing:
{% if request.user.is_authenticated %}
But the problem with this code is that the message appears each time, even when you reload the page.
The way I've done this is to use Django's login signals and messaging framework.
First, in your models.py of the app that manages users (or somewhere that gets instantiated when your Django Project is started), you can do something like this:
from django.contrib.auth.signals import user_logged_in
from django.contrib import messages
def login_tasks(sender, user, request, **kwargs):
messages.add_message(
request,
messages.INFO,
f"Welcome {user.username}, you have logged in.",
}
user_logged_in.connect(login_tasks)
Then in your template:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
More on Django's login signals: https://docs.djangoproject.com/en/3.1/ref/contrib/auth/#module-django.contrib.auth.signals
More on Django's messages framework: https://docs.djangoproject.com/en/3.1/ref/contrib/messages/
Good luck!

Display messages on LogoutView

I'm using the messages framework for basic things like success messages on user login. This is working fine.
I can't get it to work when a user logs out, however. I'm not a web-developer so not particularly strong with django so not sure what i'm doing wrong - there are similar issues:
django message when logout
Django How to add a logout successful message using the django.contrib.auth?
with solutions in using signals - before trying that I'd like to understand why my code below isn't working. I'm clearly missing something!
Note in my template i've added a conditional to print some text if there are no messages - this text does print out so my messages.html is definitely being included.
views.py
class LogoutFormView(SuccessMessageMixin,LogoutView):
template_name = 'users/logout.html'
success_message = "Successfully logged out."
class login_view(SuccessMessageMixin,LoginView):
template_name = 'users/login.html'
success_message = "Successfully logged in."
def get_success_url(self):
return reverse('recordings:projects')
messages.html
{% if messages %}
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">×</span> </button>
{{ message }}
</div>
{% endfor %}
{% endif %}
in the template both my login redirect and logout.html extends:
<div class="container-fluid mt-3 pl-5 pr-5">
{% block messages %}
{% if messages %}
test-messages
{% else %}
test-no-messages
{% endif %}
{% include "common/messages.html" %}
{% endblock %}
</div>
LogoutView is not a FormView so using the SuccessMessageMixin does not make sense here as it would not do anything
LogoutView calls the logout method and the logout method calls request.session.flush() which will delete any messages when using the SessionStorage backend
You could either move to using the CookieStorage backend, as I don't think this would be affected by request.session.flush or you could override the dispatch method of LogoutView and add the message after request.session.flush has been called although I'm not sure if this will work
def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
messages.add_message(request, messages.INFO, 'Successfully logged out.')
return response

Set the data in render method after pre-declaration in Django

I have declared the variable as given below:
response = render( request, 'authme/login.html', {} )
At some point of time, I need to set the temporary cookie and pass the value of temporary cookie in the view.
I tried the following ways to set the data as given below:
response['message'] = "Login Failed: Please try again"
response.message = "Login Failed: Please try again"
Can anyone suggest how can I set the message part using variable "response", in the same way, How do we use for setting cookie, PFB:
response.set_cookie('message','Login Failed: Please try again')
So that it is equivalent to this line of statement:
response = render( request, 'authme/login.html', {"message":"Login Failed: Please try again"})
Please refer to Django messages framework, you can pass messages from views:
messages.error(request, 'Login Failed')
messages.success(request, 'Successfully Logged in.'
And you can use these messages using Jinja2 in your HTML:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

Rise error when try to delete protected foreign key in Django

I want the user to see an error message when he tries to delete a value that is being used as PROTECTED Foreign key for another table, and the table is not empty which means there are values under this Foreign key.. it returns back an error for me in debug mode but I want an error message for end user ...
view.py
def cat_delete(request, pk):
instance = get_object_or_404(Categories, pk=pk)
instance.delete()
return redirect('/')
urls.py
path('category/<int:pk>/delete/', views.cat_delete, name="cat_delete"),
HTML
<button type="button" class="btn btn-danger" >تأكيد المسح</button>
You can use the Django Messages Framwork
Your cat_delete view:
from django.contrib import messages
...
def cat_delete(request, pk):
instance = get_object_or_404(Categories, pk=pk)
try:
instance.delete()
except Exception as e:
messages.error(request, "Your error message")
return redirect('/')
In your html template, error message will be visible under messages variable. You can use the following snippet to display it:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

Messages are not being flashed when form errors in Flask

I've edited my question to be more clear. When I validate my form and it has errors, I flash my message but this does not end up rendered in my template:
#app.route('doit', methods=["GET", "POST"])
def doit():
form = MyForm()
if form.validate_on_submit():
flash('success')
else:
if form.errors:
print "You've got errors!"
flash('You have some errors')
print session['_flashes']
return render_template('test.html')
My template for displaying messages:
{% with messages = get_flashed_messages() %}
{{ messages }}
<br/>
{{ session }}
{% endwith %}
When I submit my form with errors, I flash flash("You have some errors"), and I DO see _flashes in the session holding my error message when I print my session to console:
# my console output
You've got errors!
[('message', 'You have some errors')]
However, when the template renders, {{ session }} does not have _flashes at all, and so get_flashed_messages() is always an empty list. No message is flashed as a result.
What am I doing wrong?
Okay guys, I was being rather dumb (again). Turns out the form was being POSTed through AJAX, but the result of the call was was expecting a JSON format and not the entire HTML template.
I've switched to returning a json response instead, and now it is fine.
The function get_flashed_messages() returns a list, which you should iterate over and print out the messages within, like this:
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% else %}
No messages.
{% endif %}
{% endwith %}

Categories

Resources