238👍
✅
You can do that using the @receiver
decorator:
from django.dispatch import receiver
@receiver(post_save, sender=Model1)
@receiver(post_save, sender=Model2)
@receiver(post_save, sender=Model3)
def my_signal_handle(sender , **kwargs)
# some code here
43👍
Per the Django documentation on receivers, receivers by default do not need to be connected to a specific sender. So what you’re describing is default Django functionality.
In other words, to do this using the @receiver
decorator you simply don’t specify a sender in the decorator. For example:
@receiver(post_save) # instead of @receiver(post_save, sender=Rebel)
def set_winner(sender, instance=None, created=False, **kwargs):
list_of_models = ('Rebel', 'Stormtrooper', 'Battleground')
if sender.__name__ in list_of_models: # this is the dynamic part you want
if created: # only run when object is first created
... set the winner ...
This assumes models that look like:
class Rebel(models.Model):
...
class Stormtrooper(models.Model):
...
class Battleground(models.Model):
...
- [Django]-405 "Method POST is not allowed" in Django REST framework
- [Django]-How do you configure Django for simple development and deployment?
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
21👍
You can skip model_name
and you will connect to all models post_save. Then you can filter if you are in right model in the handler:
post_save.connect(foo)
def foo(sender, **kwargs):
if sender not in [FooModel, BarModel]:
return
... actual code ...
or you can filter based on field in model:
def foo(sender, **kwargs):
if not getattr(sender, 'process_by_foo', False):
return
... actual code ...
- [Django]-Django: Model Form "object has no attribute 'cleaned_data'"
- [Django]-Django manage.py runserver invalid syntax
- [Django]-Change a form value before validation in Django form
13👍
def receiver_with_multiple_senders(signal, senders, **kwargs):
"""
Based on django.dispatch.dispatcher.receiver
Allows multiple senders so we can avoid using a stack of
regular receiver decorators with one sender each.
"""
def decorator(receiver_func):
for sender in senders:
if isinstance(signal, (list, tuple)):
for s in signal:
s.connect(receiver_func, sender=sender, **kwargs)
else:
signal.connect(receiver_func, sender=sender, **kwargs)
return receiver_func
return decorator
👤C S
- [Django]-Add a custom button to a Django application's admin page
- [Django]-Rendering a value as text instead of field inside a Django Form
- [Django]-How do I go straight to template, in Django's urls.py?
Source:stackexchange.com