Extending the user model in django.
Assign a custom user at login in the Django web application framework.
This custom backend allows you assign a subclass of the django user at login.
Say you have a custom user Foo:
class Foo(User):
magic = model.CharField(...)
when a Foo logs in you want him to be a Foo, and not a user. So when you call
def bar(request)
user = request.user
# user is a Foo, automatically
user.magic = "card trick"
# works
This is an extension of
http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
The only limitation as written is that it takes over the group attribute of the user
definition. The user object subclass will be the group name for the user. If no group
is assigned then the user is a standard User. This can be easily changed, but I don't need
the group functionality for my app.
Name the file auth_backends.py and put it at your app docroot.
Modify settings.py as such:
AUTHENTICATION_BACKENDS = (
'djdemo.auth_backends.CustomUserModelBackend',
)
This is my first Django hack.
"""
auth_backends.py
Created by Joel Bremson on 2009-09-07.
joel3000 @t gmail
"""
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model
from django.contrib.auth.models import User
import pdb
class AutopiaUserModelBackend(ModelBackend):def authenticate(self, username=None, password=None):
try:
self._user_id=User.objects.get(username=username).id
user = self.user_class.objects.get(username=username)
if user.check_password(password):
return user
except self.user_class.DoesNotExist:
return None
def get_user(self, user_id):try:
self._user_id = user_id
return self.user_class.objects.get(pk=user_id)
except self.user_class.DoesNotExist:
return None
@propertydef user_class(self):
if not hasattr(self, '_user_class'):
try: # group is used only for subclass info - only one entry allowed (className)
# for the user group
group = User.objects.get(id=self._user_id).groups.values()[0]['name']
except IndexError:
# user is a regular user
self._user_class = get_model("auth","user")
else:
self._user_class = get_model("mpg",group)
if not self._user_class:
raise ImproperlyConfigured('Could not get custom user model')
return self._user_class