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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With