6. What signals are raised by Django during object creation or update?¶
Django provides signals which allows hooking into a model objects creation and deletion lifecycle. The signals provided by Django are
pre_init
post_init
pre_save
post_save
pre_delete
post_delete
Among these, the most commonly used signals are pre_save
and post_save
. We will look into them in detail.
6.1. Signals vs overriding .save¶
Since signals can be used for similar effects as overriding .save
, which one to use is a frequent source of confusion. Here is when you should use which.
- If you want other people, eg. third party apps, to override or customize the object
save
behaviour, you should raise your own signals - If you are hooking into the
save
behavior of an app you do not control, you should hook into thepost_save
orpre_save
- If you are customizing the save behaviour of apps you control, you should override
save
.
Lets take an example of a UserToken
model. This a class used for providing authentication and should get created whenever a User
is created.
class UserToken(models.Model):
token = models.CharField(max_length=64)
# ...