Question

I found this following snippet of code in Django documentation: for log in. I have a different version below, which I want to know if it makes any difference from the above one.

I do a if request.user check. An user gets attached to request only if he is authenticated/logged in correct?

from documentation:

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
    else:
        # Return an 'invalid login' error message.

my version:

from django.contrib.auth import authenticate, login

    def my_view(request):
        if request.user:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
    else:
        # Return an 'invalid login' error message.
Was it helpful?

Solution

There is a huge difference between the two versions.

From the docs,

If the current user has not logged in, this attribute will be set to an 
instance of AnonymousUser, otherwise it will be an instance of User.

so you would want:

if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.

OTHER TIPS

I put together a quick and dirty Django project for user set up and auth with PostgresSQL. Feel free to check it out, especially the auth.py file in the users app. You can customize this to whatever best fits your project.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top