Omar Jandali
Omar Jandali

Reputation: 824

Check if there is someone logged in Django

I have a new django project I am working on. I am integrating Djangos user login and logout service that comes with the framework. I have a view and within the view, I want to check and see if there is a user object in the request.user. if there is not, I want to redirect to login page. If there is a user in the request.user, I want to display the users home page. how can I do this. Here is my code:

def home(request):
    if not request.user:
        return redirect('login')
    else:
        User = request.user
        profile = Profile.objects.get(user = User)
        parameters = {
            'user':User,
            'profile':profile,
        }
        return render(request, 'user/home.html', parameters)

It works if there is a user logged in but doesnt work if there is no user logged in...

Upvotes: 0

Views: 6087

Answers (3)

K.A
K.A

Reputation: 1659

you have two options,

option 1:

to check if user is logged-in (authenticated user) inside your views, use "is_authenticated", as the following example:

from django.shortcuts import render, redirect

def home(request):
    if not request.user.is_authenticated:
        print('no, the user is not logged-in')
        return redirect('login')
      
    return render(request, 'user/home.html', parameters)

option 2:

by using'login_required' decorator :

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required(login_url='/login')  #url you want to redirected to 
def home(request):
    return render(request, 'user/home.html', parameters)

this is just example , and change it based on your requirements.

i hope this helpful for you .

Upvotes: -1

bruno desthuilliers
bruno desthuilliers

Reputation: 77942

Django provides a decorator for this:

from django.contrib.auth.decorators import login_required

@login_required
def home(request):
    # at this point you know you _always_ have an authenticated user
    user = request.user
    profile = Profile.objects.get(user=user)
    context = {
        'user':user,
        'profile':profile,
    }
    return render(request, 'user/home.html', context)

Upvotes: 2

Exprator
Exprator

Reputation: 27543

def home(request):
    if not request.user.is_authenticated:
        return redirect('login')
    else:
        User = request.user
        profile = Profile.objects.get(user = User)
        parameters = {
            'user':User,
            'profile':profile,
        }
        return render(request, 'user/home.html', parameters)

you need to check whether the user is authenticated or not, if you check request.user django will return anonymous user as default

Upvotes: 5

Related Questions