Storing additional information about users
If you'd like to store additional information related to your users,
Django provides a method to specify a site-specific related model --
termed a "user profile" -- for this purpose.
To make use of this feature, define a model with fields for the
additional information you'd like to store, or additional methods
you'd like to have available, and also add a OneToOneField named user
from your model to the User model. This will ensure only one instance
of your model can be created for each User. For example:
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
accepted_eula = models.BooleanField()
favorite_animal = models.CharField(max_length=20, default="Dragons.")
To indicate that this model is the user profile model for a given
site, fill in the setting AUTH_PROFILE_MODULE with a string consisting
of the following items, separated by a dot:
The name of the application (case sensitive) in which the user profile model is defined (in other words, the name which was passed to
manage.py startapp to create the application).
The name of the model (not case sensitive) class.
For example, if the profile model was a class named UserProfile and
was defined inside an application named accounts, the appropriate
setting would be:
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
When a user profile model has been defined and specified in this
manner, each User object will have a method -- get_profile() -- which
returns the instance of the user profile model associated with that
User.
The method get_profile() does not create a profile if one does not
exist. You need to register a handler for the User model's
django.db.models.signals.post_save signal and, in the handler, if
created is True, create the associated user profile:
in models.py
from django.contrib.auth.models import User from
django.db.models.signals import post_save
# definition of UserProfile from above
# ...
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)