1
votes

I am working on a Django Project:

I have a login form with username and password

Generally i observed authenticate function is used to authenticate a user and pass i.e

user = authenticate(username, password)

I tried to understand the authenticate function but i found it is not so easy.

Instead of using the authenticate function i want to check the authentication the following way:

1) check if the username exists

2) check if the password matches

3) check if is_active is true.

Which i can do by the following way:

username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')

# check if user exists
try:
    user = User.objects.get(username=username)
except User.DoesNotExist:
    user = None

#check if user is_active
if user.is_active:
    user_active = true
else
    user_active = false

#check the password

if user_active:
    password_match = user.check_password(password):
else:
    password_match = false

if password_match:
    msg = "Login Successful"
else:
    msg = "Login Failed"

Will the above serve the same purpose as authenticate function or is there something else to be checked.

1
If this is causing difficulties, you must switch to easier tasks. Authentication and authorization are very complex and sensitive tasks. You need to practice working on simpler problems. Besides it has no practical value as Django authentication implementation is good and if you're not happy, there's excellent django-allauth package.Eugene Morozov
It is good that you are trying to understand Django authentication, but don't beat yourself up because you don't understand it. Use it anyway, because it has been implemented really well. If you really want to understand it, post that question on SO.saketk21

1 Answers

2
votes

authenticate method runs through all authenticate backends and call it's authenticate method.

Default Django's auth backend is ModelBackend. If you check it's authenticate method you'll see that it's already include all described by you steps.