3
votes

http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/

When it comes to extending the User model, the above article list two methods: the old way (ForeignKey) and the new way (User model with inheritance). But at the same time, this article dates back to Aug 2008.

I am using Django's development version.

Would you recommend Extending the Django User model with inheritance or by using ForeignKey?

I read in a couple of posts that extending django.contrib.auth.models.User is not recommended, so I will not be looking at that.

3

3 Answers

1
votes

AFAIK, the cleaner approach - if this can fit in your project architecture - is to have a distinct user profile model, and use the AUTH_PROFILE_MODEL setting to link it up to the Django User model.

See the Django Doc about storing additional information for Users

1
votes

Dominique Guardiola is right. Use the AUTH_PROFILE_MODEL. James Bennett reiterated this in his 'Django in Depth' talk. http://www.youtube.com/watch?v=t_ziKY1ayCo&feature=related around 1hr:37mins.

  • Decide on the application where we want to house our user's profile, let's call it BngGangOfFour.
  • Define a Model class, lets name it UserProfile for clarity, and give it the extra field(s) we desire.

BngGangOfFour/models.py

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User) #notice it must contain a 1 to 1 field with the auth user.
    last_ip_address = models.CharField(max_length=20, default="")
  • Edit settings.py to designate our newly created model as the user profile.

settings.py

....
AUTH_PROFILE_MODULE = 'BngGangOfFour.UserProfile' #not case sensitive.
....
  • Access the profile directly off the user objects.

BngGangOfFour/views.py

....
def index(request):
    if request.user.get_profile().last_ip_address = "127.0.0.1":
        print("why hello me!")    
    return render_to_response('index.html', locals(), context_instance=RequestContext(request))
  • Sip a cold beer and call it a day.
0
votes

The only time you can cleanly get away with extending User via inheritance is if you're writing an auth backend which will return an instance of the appropriate model instead.