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. Browser-native date input field by kytta 4 weeks, 1 day ago
  2. Generate and render HTML Table by LLyaudet 1 month, 1 week ago
  3. My firs Snippets by GutemaG 1 month, 1 week ago
  4. FileField having auto upload_to path by junaidmgithub 2 months, 2 weeks ago
  5. LazyPrimaryKeyRelatedField by LLyaudet 2 months, 3 weeks 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.