16👍
In a view, you can use if request.user.is_authenticated():
and the variable for the current user is request.user
In a template, you can use {% if user.is_authenticated %}
and the variable for the current user is user
For redirecting a user after logging in, you can set up LOGIN_REDIRECT_URL
variable in settings.py
7👍
In .py documents
You can either use this inside every view
if not request.user.is_authenticated:
#do something
or this just before every view
@login_required
Remember that this one requires importing from django.contrib.auth.decorators import login_required
and you may also want to write LOGIN_URL = "/loginurl/"
in your settings.py
to get non-logged users redirected to an specific URL instead of the default one accounts/login
)
In .html documents
{% if not user.is_authenticated %}
Login is required
{% endif %}
Redirecting after logging in
You can either modify LOGIN_REDIRECT_URL
in settings.py
or redirect("/indexpage")
after the user has been logged in.
This last one requires importing from django.shortcuts import redirect
- Change default faker locale in factory_boy
- How to pass the remote IP to a proxied service? – Nginx
- Iterating over a Django QuerySet while deleting objects in the same QuerySet
4👍
You can also use a login required decorator before your view :
@login_required()
It redirects a user to the login page if a non logged in user tries to access your view
You will find more on this page :
https://docs.djangoproject.com/en/dev/topics/auth/default/#topic-authorization
- How does a .env file relate to Python / Django?
- Django ajax error response best practice
- Django custom login page