2

to achieve unique constraint (without repetition of default user models fields) on email-id I did this

from django.contrib.auth.models import AbstractUser class User(AbstractUser): # some extra fields class Meta: unique_together = ('email', ) 

and then in settings file AUTH_USER_MODEL = 'myApp.User'

mysql table shows both column(username and email) as UNI key.

so far looks good but when it comes to authentication I'm not sure where I'm making mistake. but its not working/loggin-in

this code works when username is the unique key and we login through username instead of email.

any help/leads would be appreciated.

EDIT: do i have to write custom modelBackend (explained here http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/) but not sure how, I see lots of code here https://github.com/django/django/blob/master/django/contrib/auth/init.py

1 Answer 1

2

You need to define backends.py like this:

from django.contrib.auth.models import User, check_password class EmailAuthBackend(object): """ Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair. """ def authenticate(self, username=None, password=None): """ Authenticate a user based on email address as the user name. """ try: user = User.objects.get(email=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): """ Get a User object from the user_id. """ try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None 

And in your settings file add this:

AUTHENTICATION_BACKENDS = ('backends.EmailAuthBackend',) 

This will enable the login with email.

For more details visit this.

Sign up to request clarification or add additional context in comments.

2 Comments

It has been extended from 'object' as you are not using any functionality from 'ModelBackend'. You can extend from 'ModelBackend' if you can find something reusable. backends.py ideally shoud be in your 'authentication' app (if you have such an app).
For future readers: (as it was in my case), make sure you import valid usermodel, if you have created custom User model. and change according.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.