How to Create a User Profile Model in Django (OneToOneField)

3D visualization of a User avatar connected via a rigid pipe to a Profile folder, representing a Django OneToOneField.

You have a Django User model, but it only has username, email, etc. What if you want to add a bio, a profile_picture, or a website_url? Building a Django User Profile Model is the way to add extra fields for user information.

Do not try to modify the built-in User model. The “best practice” is to create a separate Profile model that is linked to the User model.

Step 1: The OneToOneField

This is the magic. A OneToOneField is just like a ForeignKey, but it guarantees that a User can only have one Profile, and a Profile can only have one User.

Open pages/models.py (or a dedicated users/models.py):

from django.db import models
from django.conf import settings

# This assumes you have a Post model
class Post(models.Model):
    # ...
    pass

# This is the new model
class Profile(models.Model):
    # Link to the built-in User model
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    
    # Your new, custom fields
    bio = models.TextField(blank=True)
    profile_pic = models.ImageField(upload_to='profile_pics/', blank=True, null=True)

    def __str__(self):
        return f"{self.user.username}'s Profile"

Run makemigrations and migrate!

Step 2: Automatically Create a Profile

What happens when a new user signs up? We need to automatically create a Profile for them. We use Signals for this.

Create a new file, e.g., pages/signals.py:

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from .models import Profile

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_profile_for_new_user(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

Now you just need to “register” this signal in your pages/apps.py file. This is the cleanest, most automatic way to keep your models in sync.


Key Takeaways

  • To add extra fields like bio or profile picture, create a separate Django User Profile Model linked to the User model.
  • Use a OneToOneField to establish a one-to-one relationship between the User and Profile models.
  • Automatically create a Profile whenever a new user signs up by using Signals in your Django project.

Similar Posts

Leave a Reply