Django Signals

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


Class/MethodThe Why
UserProfile() ClassThe UserProfile class extends the Django default User Model.
create_profile() methodThe create_profile() method is executed, whenever a Django User model post_save signal is released.


Now, the details.

Django signals is a way to inform your app of certain tasks (such as a model pre- or post-save or delete) when it takes place.

These signals allow you to perform actions of your choice immediately that signal is released.

For instance, anytime a new Django User is created, the User Model releases a signal, with associating params such as sender=User allowing you to specifically target your listening of signals to a specific activity that happens, in this case, a new user creation.

In the above example, the intention is to have a UserProfile object created, immediately after a User object is created. Therefore, by listening to a post_save signal from the User model (the default Django User Model) specifically, we create a UserProfile object just after a new User is created.

The Django Documentation provides extensive documentation on all the possible signals available.

However, the above example is to explain in practical terms a typical use case when using Signals can be a useful addition.

"With great power, comes great responsibility". It can be tempting to having signals scattered across your entire app or project just because they're awesome. Well, Don't. Because they're cool doesn't make them the go-to solution for every simple situation that comes to mind.

Signals are great for, as usual, not everything. Login/Logouts, signals are great. Key models releasing signs, like the User Model, if fine.

Creating signals for each and every model in your app can get overwhelming at a point, and defeat the whole idea of the sparring use of Django Signals.

Do not use signals when (based on Two Scoops of Django book):

  • The signal relates to one particular model and can be moved into one of that model’s methods, possibly called by save().
  • The signal can be replaced with a custom model manager method.
  • The signal relates to a particular view and can be moved into that view

It might be okay to use signals when:

  • Your signal receiver needs to make changes to more than one model.
  • You want to dispatch the same signal from multiple apps and have them handled the same way by a common receiver.
  • You want to invalidate a cache after a model save.
  • You have an unusual scenario that needs a callback, and there’s no other way to handle it besides using a signal. For example, you want to trigger something based on the save() or init() of a third-party app's model. You can't modify the third-party code and extending it might be impossible, so a signal provides a trigger for a callback.

Got any Django Question?