title: Log in user using either email address or username in Django
body: <p>I am trying to create an auth backend to allow my users to log in using either their email address or their username in Django 1.6 with a custom user model. The backend works when I log in with a user name but for some reason does not with an email. Is there something I am forgetting to do?</p>
  
  <pre><code>from django.conf import settings
  from django.contrib.auth.models import User
  
  class EmailOrUsernameModelBackend(object):
      """
      This is a ModelBacked that allows authentication with either a username or an email address.
  
      """
      def authenticate(self, username=None, password=None):
          if '@' in username:
              kwargs = {'email': username}
          else:
              kwargs = {'username': username}
          try:
              user = User.objects.get(**kwargs)
              if user.check_password(password):
                  return user
          except User.DoesNotExist:
              return None
  
      def get_user(self, username):
          try:
              return User.objects.get(pk=username)
          except User.DoesNotExist:
              return None
  </code></pre>
  
  <p>Edit: As suggested I have inherited from ModelBackend and installed it in my settings
  In my settings I have this
      AUTHENTICATION_BACKENDS = (
          'users.backends',
          'django.contrib.auth.backends.ModelBackend',
          )
  And I have changed the backend to this:</p>
  
  <pre><code>from django.conf import settings
  from django.contrib.auth.models import User
  from django.contrib.auth.backends import ModelBackend
  class EmailOrUsernameModelBackend(ModelBackend):
      """
      This is a ModelBacked that allows authentication with either a username or an email address.
  
      """
      def authenticate(self, username=None, password=None):
          if '@' in username:
              kwargs = {'email': username}
          else:
              kwargs = {'username': username}
          try:
              user = User.objects.get(**kwargs)
              if user.check_password(password):
                  return user
          except User.DoesNotExist:
              return None
  
      def get_user(self, username):
          try:
              return User.objects.get(pk=username)
          except User.DoesNotExist:
              return None
  </code></pre>
  
  <p>Now I get an <code>Module "users" does not define a "backends" attribute/class</code> error.</p>