Checking every page if a user is logged in - Django

Updated on Oct. 8, 2017 | 154 |   django,

Imagine, we have a page directory, www.example/home/. Here, /home/ directory can only be accessed after login. But what if a user tries to enter directly to this link directory without login. Currently, it will simply let the anonymous user see the page which is a huge problem as we only want the authenticated or logged in users see this page with their personalized information. Let’s prevent this following the step below.

Step 1: For every view, you want login to be a requirement set the code below. 

def home(request):

    if request.user.is_authenticated:

    # here goes other code of this view

    else:

       #returns to a directory if a user is not logged in

       return redirect('/login/'

request.user.is_authenticated is a Boolean attribute which is True if a user is logged in, else it is a False.

That’s it! Now, anyone without being logged in can’t see the page.