Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the User model with custom fields in Django

What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes).

I've already seen a few ways to do it, but can't decide on which one is the best.

like image 556
Farinha Avatar asked Sep 04 '08 16:09

Farinha


2 Answers

Note: this answer is deprecated. see other answers if you are using Django 1.7 or later.

This is how I do it.

#in models.py from django.contrib.auth.models import User from django.db.models.signals import post_save  class UserProfile(models.Model):       user = models.OneToOneField(User)       #other fields here      def __str__(self):             return "%s's profile" % self.user    def create_user_profile(sender, instance, created, **kwargs):       if created:          profile, created = UserProfile.objects.get_or_create(user=instance)    post_save.connect(create_user_profile, sender=User)   #in settings.py AUTH_PROFILE_MODULE = 'YOURAPP.UserProfile' 

This will create a userprofile each time a user is saved if it is created. You can then use

  user.get_profile().whatever 

Here is some more info from the docs

http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

Update: Please note that AUTH_PROFILE_MODULE is deprecated since v1.5: https://docs.djangoproject.com/en/1.5/ref/settings/#auth-profile-module

like image 30
Raisins Avatar answered Sep 21 '22 15:09

Raisins


The least painful and indeed Django-recommended way of doing this is through a OneToOneField(User) property.

Extending the existing User model

If you wish to store information related to User, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.

That said, extending django.contrib.auth.models.User and supplanting it also works...

Substituting a custom User model

Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.

[Ed: Two warnings and a notification follow, mentioning that this is pretty drastic.]

I would definitely stay away from changing the actual User class in your Django source tree and/or copying and altering the auth module.

like image 109
Ryan Duffield Avatar answered Sep 17 '22 15:09

Ryan Duffield