Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-registration: how do I check whether the user is logged in before displaying a page

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!

like image 354
CuriousMind Avatar asked Jan 08 '13 16:01

CuriousMind


2 Answers

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

like image 197
msc Avatar answered Nov 06 '22 14:11

msc


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

like image 20
zurfyx Avatar answered Nov 06 '22 15:11

zurfyx