Adding a class-based signal handler
You can do it:
class ActionSignals(object): def __init__(self, *args, **kwargs):
Then connect the signal handler:
handler = ActionSignals() post_save.connect(handler)
This uses the python "magic" __call__ , which allows you to use an instance of a class as a function.
Avoiding duplicates
Be careful when you add handlers to your code, as you can create duplicates. For example, if you want to put the second bit of code in the root module, it will add a handler each time the module is imported.
To avoid this, you can do the following :
post_save.connect(handler, dispatch_uid="my_unique_identifier")
As @Alasdair pointed out, you can add handlers to AppConfig.ready() (and this is the recommended place for this), although you can usually do this anywhere if you don't want to create unwanted duplicates.
See "Where should this code live?" in this document .
source share