What's the best way to extend the User model in Django?

ghz 1years ago ⋅ 7711 views

Question

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](http://scottbarnham.com/blog/2008/08/21/extending- the-django-user-model-with-inheritance/) [ways](http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user- model/) to do it, but can't decide on which one is the best.


Answer

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

[Extending the existing User

model](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending- the-existing-user-model)

If you wish to store information related to User, you can use a [one-to- one relationship](https://docs.djangoproject.com/en/dev/ref/models/fields/#ref- onetoone) 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](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#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.