Trigering post_save signal only after transaction has completed

I think the simplest way is to use transaction.on_commit(). Here’s an example using the models.Model subclass Photo that will only talk to Elasticsearch once the current transaction is over: from django.db import transaction from django.db.models.signals import post_save @receiver(post_save, sender=Photo) def save_photo(**kwargs): transaction.on_commit(lambda: talk_to_elasticsearch(kwargs[‘instance’])) Note that if the transaction.on_commit() gets executed while not in an active … Read more

Django – signals. Simple examples to start

You can find very good content about django signals over Internet by doing very small research. Here i will explain you very brief about Django signals. What are Django signals? Signals allow certain senders to notify a set of receivers that some action has taken place Actions : model’s save() method is called. django.db.models.signals.pre_save | … Read more

Disconnect signals for models and reconnect in django

For a clean and reusable solution, you can use a context manager: class temp_disconnect_signal(): “”” Temporarily disconnect a model from a signal “”” def __init__(self, signal, receiver, sender, dispatch_uid=None): self.signal = signal self.receiver = receiver self.sender = sender self.dispatch_uid = dispatch_uid def __enter__(self): self.signal.disconnect( receiver=self.receiver, sender=self.sender, dispatch_uid=self.dispatch_uid, weak=False ) def __exit__(self, type, value, traceback): self.signal.connect( … Read more

Raise 404 and continue the URL chain

This is certainly view logic; all urls.py is for is for matching URL patterns, not performing validation. You can use the Http404 exception to handle this. from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response(‘polls/detail.html’, {‘poll’: p}) Alternatively, you may find the get_object_or_404 or get_list_or_404 methods, which … Read more

How to use Django model inheritance with signals?

You could register the connection handler without sender specified. And filter the needed models inside it. from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save) def my_handler(sender, **kwargs): # Returns false if ‘sender’ is NOT a subclass of AbstractModel if not issubclass(sender, AbstractModel): return … Ref: https://groups.google.com/d/msg/django-users/E_u9pHIkiI0/YgzA1p8XaSMJ