tags:

views:

22

answers:

1

Hi All,

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.

+1  A: 

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.

Manoj Govindan
thanks for your reply manoj, this one would work fine for the front-end user updates. But if we change the address through the admin panel, this view would not be called and hence this signal would not be sent.
anand
Updated answer. See above.
Manoj Govindan
its a separate model with user as a foreign key.. so i guess User.save() is not possible in this case?
anand
ok, got you.. Thanks a lot!
anand