Display messages on LogoutView - python

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

Related

can't login with facebook using allauth library using Django because of CSRF token and gave me CSRF verification failed. Request aborted

i have a server deployed in AWS using Django and every thing working fine until i tap on login with facebook Button it shows the normal facebook login popup and after typing my email and password instead of going to the next page it gave me CSRF verification failed. Request aborted.
as you can see i've {% csrf_token %} in the code for showing login with facebook button using js_sdk:
{% extends 'restaurant/base_auth.html' %}
{% load bootstrap4 %}
{% block title %}Akalat-Shop{% endblock %}
{% block heading %}Akalat-Shop - Sign In{% endblock %}
{% block content %}
{% load socialaccount %}
{% providers_media_js %}
Login with Facebook
<form action="" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<button type="submit" class="btn btn-primary btn-block">Sign In</button>
</form>
<div class="text-center mt-3">
Become a Restaurant
</div>
{% endblock %}
also i tried those in settings.py :
LOGIN_REDIRECT_URL = '/'
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'
SOCIAL_AUTH_REDIRECT_IS_HTTPS = True
//all configurations of facebook login
my views.py i've checked also for using #csrf_exempt:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
#login_required(login_url="/restaurant/sign_in/")
def restaurant_home(request):
return redirect(restaurant_order)
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
#login_required(login_url="/restaurant/sign_in/")
def restaurant_order(request):
if request.method == "POST":
order = Order.objects.get(id=request.POST["id"])
if order.status == Order.COOKING:
order.status = Order.READY
order.save()
orders = Order.objects.filter(restaurant = request.user.restaurant).order_by("-id")
return render(request, 'restaurant/order.html', {"orders": orders})
my configurations in facebook dashboard for callback url in the screenshot below:
i don't know where is the problem but may be from using js_sdk in facebook login caused this block and thanks in advance for helping ✨🤝

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!

Flask form validation error prompt message

I made a form to reset password, when I submit the form with an empty password, the error prompt words I set in views.py didn't show up at the <span> I left in a HTML, a default Fill out this field showed instead.
*fisrt one is old password, second one is new password
In forms.py:
class PwdForm(FlaskForm):
old_pwd = PasswordField(
label="OldPassword",
validators=[
DataRequired("Please input old password")
]
)
submit = SubmitField(
"Confirm"
)
In views.py:
#admin.route("/pwd_reset/", methods=["GET", "POST"])
#admin_login_req
def pwd_reset():
form = PwdForm()
if form.validate_on_submit():
data = form.data
admin = Admin.query.filter_by(name=session["admin"]).first()
from werkzeug.security import generate_password_hash
admin.pwd = generate_password_hash(data["new_pwd"])
db.session.add(admin)
db.session.commit()
flash("ok, now use your new password to login", "ok")
redirect(url_for("admin.logout"))
return render_template("admin/pwd_reset.html", form=form)
In html:
<label for="input_pwd">{{ form.old_pwd.label }}</label>
{{ form.old_pwd }}
{% for err in form.old_pwd.errors %}
<span style="color: #ff4f1f">{{ err }}</span>
{% endfor %}
How to make my own prompt message show up
I think you mean how do you get your flash message to display? Use the following code in your base template page or in each page. See: Message Flashing
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="flashes">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}

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

Categories

Resources