Mr. Sigma.
Mr. Sigma.

Reputation: 435

What exactly is the parameter 'username' in authenticate function django?

From documentation about django.contrib.auth.authenticate function, we find -

Use authenticate() to verify a set of credentials. It takes credentials as keyword arguments, username and password for the default case, checks them against each authentication backend, and returns a User object if the credentials are valid for a backend.

Now, my question is what do they mean by username?

Actually, I have been sending email as a username because I wanted to check credentials based on email (primary key) rather than username (whatever it means) but it didn't work... But I named one of a column of my model to username but it still didn't work... So, I wonder what do they mean by username exactly.

My code that didn't work -

email = request.POST['email']
#email = request.POST['username'] Changed email column-name to username but didn't work!
password = request.POST['password']
user = authenticate(request, username=email, password=password)
print (user) ## None

Upvotes: 0

Views: 440

Answers (1)

Victor Hug
Victor Hug

Reputation: 81

The default UserModel contains the username Attribute (column of the model), this is used to identify the user in the authentication backend. You have two possibilities:

  • Create a new UserModel without the username Attribute to use the email to authenticate (You have to create a new Authentication Backend)

  • Just change the authentication backend to authenticate with the email or both and keep the username Attribute

To replace the username with the email:
https://medium.com/@ramykhuffash/django-authentication-with-just-an-email-and-password-no-username-required-33e47976b517
Django - Login with Email

If you just want to change the authentication backend, to authenticate with the email:
Django - Login with Email

P.S. The username argument of the authenticate function shouldn't be renamed, even if you use the email instead.

Upvotes: 1

Related Questions