I am working on a django project, where I want to implement a signal which should be called when some user address is changed. I have seen the built-in signals but they do not seem to work in my case, because if i use save that will be called in other save events as well and though I am able to create a custom signal, I could not find out, how should I call this ?
Please suggest.
Thanks in advance.
There are 3 types of signal. pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model's instance (method delete()) this signal is thrown.
To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.
The Django Signals is a strategy to allow decoupled applications to get notified when certain events occur. Let's say you want to invalidate a cached page everytime a given model instance is updated, but there are several places in your code base that this model can be updated.
django.db.models.signals. post_save. Like pre_save , but sent at the end of the save() method. Arguments sent with this signal: sender.
Start by defining a custom signal. A custom signal here is a sub class of django.dispatch.Signal
. This code can live in app/signals.py
.
from django.dispatch import Signal
user_address_changed = Signal(providing_args=["user"])
Next, make sure you send this signal when your user's address is changed. Depending on how you have defined User
and Address
this can be done in different places. Let us assume that there is a view that lets users update their Address
models. This code is presumably in app/views.py
.
from app import signals
def update_address(request, *args, **kwargs):
# all the changes go well.
signals.user_address_changed.send(sender=None, user=request.user)
# Render to template etc.
Now you need to set up a receiver for this signal.
from app.signals import user_address_changed
def handle_user_address_change(sender, **kwargs):
"""Trap the signal and do whatever is needed"""
user = kwargs['user']
# Write to log, update db, send mail etc.
user_address_changed.connect(handle_user_address_change)
Update
(After reading comment; the OP explains that there is no separate view that updates address) In that case you can try to override User.save()
to send out this signal. I say "try" because I do not know if you are using your own User
class or auth.User
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With