Django 1.7 User login via Email or Username

2,194 views
Skip to first unread message

Frankline

unread,
Oct 15, 2014, 4:35:52 AM10/15/14
to django...@googlegroups.com
Hi all,

Just started looking at Django 1.7. I've followed the tutorials on https://docs.djangoproject.com/en/1.7/.

However, I find myself in a position where I need to login users based on either email or username, AND NOT just the username. I want my users to register using email addresses. This presents some issues with the standard Django user implementation since the authentication backend is still going to look for the username when logging in. 

I am keen to know how developers here implement this in their own Django 1.7 projects. And also what user models are preferable: AbstractUser or AbstractBaseUser.

Any links to example tutorials will also be greatly appreciated.

Regards,
Frankline

monoBOT

unread,
Oct 15, 2014, 4:52:57 AM10/15/14
to django...@googlegroups.com
You can implement an alternative authentication backend like so:

on your settings:

AUTHENTICATION_BACKENDS = (
    'your_app.backend.EmailBackend',
    'django.contrib.auth.backends.ModelBackend'
    )

and on "your_app.backends":

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.contrib.auth import get_user_model


class EmailBackend(object):
    def authenticate(self, username=None, password=None):
        user_cls = get_user_model()
        try:
            user = user_cls.objects.get(email=username)
            if user.check_password(password):
                return user
        except user_cls.DoesNotExist:
            return None
        except:
            return None

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


So the app checks if the user can be authenticated via your backend and if fails goes to the normal authentication backend.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEAUGdUzZ3ytWQPpBihXOJm2vE7ZxBRhXYQ3mMwgjr2xJR4bpw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.



--
monoBOT
Visite mi sitio(Visit my site): monobotsoft.es/blog/

carlos

unread,
Oct 16, 2014, 1:12:08 PM10/16/14
to django...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages