I followed this page to set up a django registration site. It's pretty awesome, and registration and authentication are nicely wrapped.
But, it doesn't show me, how do I check if a user is logged in, who this user is, before displaying a webpage? and how do I direct the user to a new page after logged in?
Thanks!
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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.