[Solved]-Django-registration: how do I check whether the user is logged in before displaying a page

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

👤msc

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

👤zurfyx

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

👤ltbesh

Leave a comment