Creating a django signal to update user information

I am working on a django project where I want to implement a signal that should be called when some kind of user address changes. I saw the built-in signals, but they do not seem to work in my case, because if I use save, which will be called in other save events, and although I can create my own signal, I could not find out how I can do this to name?

Please offer.

Thanks in advance.

+6
django
source share
2 answers

Start by defining a custom signal. The custom signal here is a subclass of django.dispatch.Signal . This code may be in app/signals.py .

 from django.dispatch import Signal user_address_changed = Signal(providing_args=["user"]) 

Then make sure you send this signal when your user address is changed. Depending on how you defined User and Address , this can be done in different places. Suppose there is a view that allows users to update their Address models. This code is supposedly located 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 configure the 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 the comment, the OP explains that there is no separate view that updates the address). In this case, you can try to override User.save() to send this signal. I say "try" because I don’t know if you use your own User class or auth.User .

+16
source share

You can evaluate django-signalqueue:

https://github.com/fish2000/django-signalqueue

This is an extension for the stock signal manager that provides the AsyncSignal class. AsyncSignal callbacks can be run in a separate workflow β€” you can control the specific behavior of the asynchronous listeners that you define.

(full disclosure: I wrote it.)

+1
source share

All Articles