# Django Signals

Signals can be used to create models on the fly as required. For example, you might want to create a profile Model every time a new user is created. You would do the following:

# Create a Profile Model for every User

This code requires there to be a relationship between the profile and user models, preferably as a OneToOne relation. Import post_save to initiate the signal.

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



def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
        print('Profile was created successfully')



def save_profile(sender, instance, **kwargs):
    instance.profile.save()


post_save.connect(create_profile, sender=User)
post_save.connect(save_profile, sender=User)

Then inside of your apps.py file. Assume your Django app is called users:

from django.apps import AppConfig


class UsersConfig(AppConfig):
    name = 'users'


    def ready(self):
        import users.signals

That is it, run your code and everytime a user is created - the signal will create a Profile model related to that user.