[Answer]-Django authorization

1👍

I am not really sure what you want to achieve. As soon as a user is logged in, you can acces request.user.is_authenticated() to check for an authenticated user in your view or access request.user for the user itself.

👤Jingo

0👍

You don’t need to add users to the session; this is done automatically by the authentication middleware.

You also don’t need to manually check for users; use the login_required decorator.

Combining this, your login view becomes:

def login_user(request):
    state = "Please log in below..."
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
    else:
        return redirect('login/')

    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            state = "You're successfully logged in!"
        else:
            state = "Your account is not active, please contact the site admin."
    else:
        state = "Your username and/or password were incorrect."
    return render(request,'auth.html',{'state':state, 'info':'info'})

And in your other views:

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

@csrf_protect
@login_required
def home(request):
    return render(request, 'home.html')

In your template (from the documentation):

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}

Leave a comment