user3384985
user3384985

Reputation: 3017

Django 1.10 - how to change front end user authentication from username to email?

In Django default user authentication is integrated through Username and Password. In my project profile page, I have an option to change Username. So, it is necessary to change my authentication system in back end and front end with email and password.

Using authentication backend i can change default authentication system through email and password in admin. Here is the code -

class EmailBackend(object):
    def authenticate(self, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if getattr(user, 'is_active', False) and  user.check_password(password):
                return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

In settings.py -

AUTHENTICATION_BACKENDS = (
    'apps.account.email-auth.EmailBackend',
)

I was wondering how could i do the authentication through in front end. Already, I prepared front login page through email and password.

But see form.errors and predict must be missing any front authentication like AUTHENTICATION_BACKENDS

Thank you very much for your help!

Upvotes: 1

Views: 420

Answers (2)

Alexander Kaluzhny
Alexander Kaluzhny

Reputation: 11

There is a package django-allauth. It handles the authentication. It allows using 'email' and 'password' or 'username' and 'password' for authentication. It includes forms and everything else needed. Django-cookiecutter project template uses this package to handle authentication, so you can look there and use it as a sample.

Upvotes: 0

user3384985
user3384985

Reputation: 3017

Actually answer is within the method -

def authenticate(self, username=None, password=None, **kwargs):

In front-end, naming the user input with email wouldn't be passed within the method then form errors show up with don't match credentials. So, simply taking input as username solves the trick.

Upvotes: 1

Related Questions