Login

Case Insensitive Authentication Backend

Author:
ericflo
Posted:
March 12, 2009
Language:
Python
Version:
1.0
Score:
5 (after 5 ratings)

By enabling this backend:

AUTHENTICATION_BACKENDS = (
    'path.to.my.backends.CaseInsensitiveModelBackend',
)

Your users will now be able to log in with their username, no matter whether the letters are upper- or lower-case.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.contrib.auth.models import User
 
class CaseInsensitiveModelBackend(object):
    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(username__iexact=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None
 
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

john_nash (on April 27, 2012):

where should i put this code .. !!

#

bquinn (on February 12, 2014):

Since Django 1.5 (?) and pluggable user models, there's an alternative way to do this.

In the Manager for your user model, add a get_by_natural_key method, then you don't need to override the default auth backend.

class MyUserManager(BaseUserManager):
    def get_by_natural_key(self, username):
        return self.get(email__iexact=username)

#

Please login first before commenting.