Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 4 - Page 170 - Creating a login view #27

Open
seyyed-amirreza-hosseini opened this issue Aug 17, 2024 · 0 comments
Open

Chapter 4 - Page 170 - Creating a login view #27

seyyed-amirreza-hosseini opened this issue Aug 17, 2024 · 0 comments

Comments

@seyyed-amirreza-hosseini

There is an issue with this code below:

def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(request, username=cd['username'], password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponse('Authenticated successfully')
                else:
                    return HttpResponse('Disabled account')
            else:
                return HttpResponse('Invalid login')
    else:
        form = LoginForm()

    return render (request, 'account/login.html', {'form': form})          

The problem is that when the authenticate function is evaluated, it returns a user object if there is an active user in our database.
It means that if we have a user that is in the database but is NOT active, the authenticate function returns "None". As a result, checking if user.is_active after if user is not None is redundant because the authenticate function has already verified the user's active status.

Therefore, the user_login function can be simplified as follows:

def user_login(request):
   if request.method == 'POST':
       form = LoginForm(request.POST)
       if form.is_valid():
           cd = form.cleaned_data
           user = authenticate(request, username=cd['username'], password=cd['password'])
           if user:
               login(request, user)
               return HttpResponse('Authenticated successfully')
           else:
               return HttpResponse('Invalid login')
   else:
       form = LoginForm()

   return render (request, 'account/login.html', {'form': form})   
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant