Extending User Model with Profile

A snippet showing how to create a profile model linked to Django's User model.


# models.py

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(blank=True)
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True)
    birth_date = models.DateField(blank=True, null=True)

    def __str__(self):
        return self.user.username
  

# signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from .models import Profile

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

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()
  

# apps.py

from django.apps import AppConfig

class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'your_app'

    def ready(self):
        import your_app.signals
  

# templates/profile.html

<h2>User Profile</h2>
<p>Bio: {{ user.profile.bio }}</p>
<p>Birth Date: {{ user.profile.birth_date }}</p>
<img src="{{ user.profile.avatar.url }}" alt="Avatar">
  
Explanation:
  • We create a Profile model linked to the default User model using OneToOneField.
  • The post_save signals automatically create and update a profile when a user is created or saved.
  • We import the signals in apps.py to ensure they are registered when the app is ready.
  • You can access profile data via user.profile in templates or views.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.