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

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 %}

Related

Django flash messages showing only on the django admin page and not on the template

I have a login form and just want to display a confirmation message as soon as the user logs in. The message is being displayed, but it is displayed on the django admin page and not on the template(the web page visible to the user). I have checked almost everything like importing messages from django.contrib, checking the installed apps list, middleware list, context_processors. I don't know where am I going wrong or what am I missing. Please help!
My views.py function
def login_method(request):
loginusername = request.POST['loginusername']
loginpass = request.POST['loginpass']
user = authenticate(username=loginusername, password=loginpass)
if user is not None:
auth_login(request, user)
messages.success(request, "Successfully Logged In!")
return redirect("appHome")
else:
messages.error(request, "Invalid Credentials, Please try again!")
return redirect("home")
You have to add this piece of code in your template where you want to display the messages:
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">{{ message }}</div>
{% endfor %}
{% endif %}
and also make sure you've add 'django.contrib.messages' to your INSTALLED_APPS

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

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 %}

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

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 %}

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