Login

Multiple User subclasses custom Auth backend

Author:
ungenio41
Posted:
September 10, 2011
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

A project I'm working on requires multiple different classes of users, all with different fields/attributes. Having a single UserProfile class with a generic relation was a complete pain in practice.

So, I changed my classes to all subclass User directly and then used django-model-utils to create a custom ModelBackend that returns the appropriate class when accessing request.user.

The InheritanceQuerySet manager provided by django-model-utils makes it all possible and with only a single database query.

No need to add anything directly to the User class, by the way. Just subclass it directly with each of your custom classes:

class CustomUser1(User):
    field1 = models.CharField(...)

class CustomUser2(User):
    field2 = models.CharField(...)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from model_utils.managers import InheritanceQuerySet


class CustomUserModelBackend(ModelBackend):
    def get_user(self, user_id):
        try:
            return InheritanceQuerySet(User).select_subclasses().get(pk=user_id)
        except User.DoesNotExist:
            return None

More like this

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

Comments

rodested (on October 11, 2011):

Hello,

I'd really like to use it. How should I deploy it?

Thanks in anticipation.

#

ungenio41 (on October 12, 2011):

Well, first you put the above code in a backends.py file.

Then, in your settings.py, put the following:

AUTHENTICATION_BACKENDS = ('backends.CustomUserModelBackend',)

Then you can do something like this in one of your models.py:

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


class MyUser(User):
    picture = models.ImageField()

#

Please login first before commenting.