Creating a User Profile model in Django to hold additional user info
Creating a new user in a Django project is quite straightforward and well-documented.
But most of the time, you want to capture more data than the basic user model provided by Django. You see, the default Django user model only contains fields for the first name, last name, and email. The typical registration flow usually requires more data to be captured. In this case, the recommended way is to create a user profile model, and “link” it to the user using a one-to-one relationship.
In this post, we will show a complete example of declaring a user profile model, the registration form that contains both the user fields and the user profile fields, and finally the view that will handle the creation of the user and user profile instances in the database.
Model
class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) id_number = models.CharField(max_length=20, unique=True) occupation = models.CharField(max_length=50, blank=True) address = models.CharField(max_length=100) street_number = models.CharField(max_length=10) flat_number = models.CharField(max_length=10, blank=True) zip_code = models.CharField(max_length=10) city = models.CharField(max_length=50)
The only highlight in this model declaration is the use of OneToOneField
relationships. This means that instances of this UserProfile
model can point to one and only one instance of the User
model.
Also, note that we are not referencing directly the User
model, but we are using settings.AUTH_USER_MODEL
as recommended in the documentation to support custom-defined models. Finally, we are using on_delete=models.CASCADE
to ensure that when a User
is deleted, the "linked" UserProfile
will be deleted as well.