Class/Method | The Why |
---|---|
UserProfile() Class | The UserProfile class extends the Django default User Model. |
create_profile() method | The 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):
save()
.It might be okay to use signals when:
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.