David Reynolds

Welcome to boredom

Django Extending/subclassing a User

| Comments

I’ve been trying for the past day or so to extend the user class in django to allow me to add other fields to the model. After lots of fiddling and help from the guys in #django, I’ve finally come up with something that works, so I thought I’d stick it in here for posterity (and to remind myself how to do it in the future).

Basically, you need to do the following in your model (sorry for lack of indentations)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from django.core import meta
# following line is vital
from django.models.auth import *

# Create your models here.
class User(users.User):
      # add your custom fields here...
  section = meta.CharField(maxlength=200)
  
  class META:
           # These 2 lines are vital they are what actually make this model replace the normal user model
      replaces_module = 'auth.users'
      module_name = "users"
           # The rest of this stuff is then copied directly from the User model with with additions for your extra fields
      verbose_name = _('User')
      verbose_name_plural = _('Users')
      module_constants = {
          'SESSION_KEY': '_auth_user_id',
      }
      ordering = ('username',)
      exceptions = ('SiteProfileNotAvailable',)
      admin = meta.Admin(
          fields = (
              (None, {'fields': ('username', 'password')}),
              (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
              (_('Permissions'), {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}),
              (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
              (_('Groups'), {'fields': ('groups',)}),
              (_('Sections'), {'fields': ('section',)})
          ),
          list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff'),
          list_filter = ('is_staff', 'is_superuser'),
          search_fields = ('username', 'first_name', 'last_name', 'email'),
      )

and now the vital part…. do NOT try to install this model from whatever app you have created it in, it won’t work. I tried countless times to make it work before it was pointed out that what I actually needed to do was this:

1
python manage.py sqlreset auth | mysql $db

Obvious, when you think about it, huh?

Now it’s all pretty much working, the only remaining issue is that..

1
python manage.py createsuperuser

..does not work. This isn’t the end of the world, but if anyone has any thoughts, I’d be very pleased to hear them.

Comments