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 for the user=instance.
Previously, there was no specific place for initializing the signal code. Typically, they were imported or implemented in models.py (which was unreliable). However, with app-loading refactor in Django 1.7, the application initialization code location is well defined.
First, subclass the ProfileConfig method in apps.py within the profiles app and set up the signal in the ready method:
# apps.py
from django.apps import AppConfig
class ProfilesConfig(AppConfig):
name = "profiles"
verbose_name = 'User Profiles'
def ready(self):
from . import signals
Next, change the line mentioning profiles in your INSTALLED_APPS to a dotted path pointing to this AppConfig. So your settings should look as follows: