Signals

Ideally, every time a user model instance is created, a corresponding user profile instance must be created as well. This is usually done using signals.

For example, we can listen for the post_save signal from the user model using the following signal handler in profiles/signals.py:

from django.db.models.signals import post_save 
from django.dispatch import receiver 
from django.conf import settings  
from . import models 
 
@receiver(post_save, sender=settings.AUTH_USER_MODEL) 
def create_profile_handler(sender, instance, created, **kwargs): 
    if not created: 
        return 
    # Create the profile object, only if it is newly created 
    profile = models.Profile(user=instance) 
    profile.save() 
The profile model has passed no additional initial parameters except ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.