In Django there's a signal called post_save which gets called after a model's save() method has been called. But what happens when you needed to update the instance inside the post_save like this:
1 |
def do_stuff(sender, * * kwargs): |
2 |
kwargs[ 'instance' ].save() |
3 |
post_save.connect(do_stuff,
sender = User) |
This will fire another post_save signal that makes a recursion and local server stops. This can be solved by overriding the save() method instead and do processing there but I haven't seen a code where they override the user, instead they create profiles which isn't really what I need.
To solve the problem, you have to disconnect the signal before calling the save() method again while inside the post_save function and connect it again once its done.
1 |
def do_stuff(sender, * * kwargs): |
2 |
post_save.disconnect(do_stuff,
sender = User) |
3 |
kwargs[ 'instance' ].save() |
4 |
post_save.connect(do_stuff,
sender = User) |
5 |
post_save.connect(do_stuff,
sender = User) |
This way when the save() method is called, it never fires another post_save signal because we've disconnected it.