Django signals: How to Run Code on Model Events (e.g., post_save)

3D visualization of a database save button triggering a wireless signal to activate a distant email machine, representing Django signals.

What if you want to automatically send a welcome email every time a new user signs up? Or create a User Profile the instant a User object is created? You can do this easily using Django signals.

This is what Signals are for. They are “broadcasts” that Django sends out when certain events happen. Your code can “listen” for these signals and run a function in response.

The most common signal is post_save (it runs after a model’s .save() method is called).

Step 1: The “Receiver” Function

This is the function you want to run. Let’s create one that listens for a new User being created.

Create a new file, e.g., users/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 # Your custom Profile model

@receiver(post_save, sender=User)
def create_profile_on_user_creation(sender, instance, created, **kwargs):
    """
    Listens for a User being created and makes a Profile.
    'instance' is the User that was saved.
    'created' is a boolean (True if it's a new user).
    """
    if created:
        print(f"Signal received! Creating profile for {instance.username}...")
        Profile.objects.create(user=instance)

Step 2: Registering Your Signal

Django needs to know about your signals.py file. The best place to load it is in your app’s apps.py file.

Open users/apps.py:

from django.apps import AppConfig

class UsersConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'users'

    # Add this method
    def ready(self):
        import users.signals # This imports and registers your signals

Now, every time a new User is created (e.g., through the admin or your sign-up form), this signal will fire, and your create_profile... function will run automatically.


Key Takeaways

  • Django signals allow your code to respond to events, like sending a welcome email when a new user signs up.
  • The common signal used is post_save, which runs after a model’s .save() method is called.
  • To set up signals, create a receiver function in signals.py and register it in apps.py.
  • Once registered, the signal triggers and executes your function automatically when a new User is created.

Similar Posts

Leave a Reply