Django Custom User Authentication Backend

1
2
from django.contrib.auth.models import User, UserManager
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Introduction

In some Django projects we need to customize user model. We don’t want to go with the Django’s existing user model because we need more fields in user model. Sometimes we want to login user with the unique-id of third party service like Facebook, Twitter and etc.
In this blog I describe how to create custom user model and custom authentication backend to perform such requirements.

Creating Custom User Model

In this example I have created custom user model named as ‘Staff’. I have extended this Staff model with Django’s User model and added more fields in Member which I needed.

from django.contrib.auth.models import User, UserManager
from django.db import models

class Designation(models.Model):
key = models.CharField(max_length=5)
name = models.CharField(max_length=32)

def __unicode__(self):
return str(self.name)

class Staff(User):
"""User with app settings."""
avatar = models.ImageField(upload_to="static/member_avatar/", blank=True,
null=True)
designation = models.ForeignKey(Designation)

# Use StaffManager to get the create_user method, etc.
objects = StaffManager()

class Meta(object):
verbose_name = 'Staff'
verbose_name_plural = 'Staffs'

Changes Required in Settings File

Then, in settings.py file you have to explicitly mention custom user model and custom authentication backend.


AUTHENTICATION_BACKENDS = ('auth_backends.StaffModelBackend',)

CUSTOM_USER_MODEL = 'app.Staff'


Creating custom authentication backend

Create the custom authentication backend class and in this class we have to change user_class property method to get user instance from our custom model instead of Django’s User model. We have mentioned this class in settings file so that Django will get user instance of our custom model using this class (instead of Django’s User model).

from django.conf import settings
from django.contri

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.