gCoh
gCoh

Reputation: 3089

Django signal to recognise which view called

I have a model with two different views.

The problem is that I have a signal registered to the model, and I want to change the behaviour of the signal based on what view called the object save method.

Is there a way doing so?

Upvotes: 0

Views: 879

Answers (2)

Pedram
Pedram

Reputation: 3920

Built-in Signals are handled by django itself, so you can only achieve that by passing extra flag to the signal (if you don't want to inspect the caller):

def first_view(request):
    #...
    model_instance._through_view = 'first'
    model_instance.save()
    #...

def second_view(request):
    #...
    model_instance._through_view = 'second'
    model_instance.save()
    #...

and for your signal:

@receiver(pre_save, sender=MyModel)
def pre_save_handler(sender, instance, created, **kwargs):
    through_view = getattr(instance, '_through_view' None)

    if through_view == 'first':
        ...
    elif through_view == 'second':
        ...

Upvotes: 0

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Simple answer: no.

Longer answer: well, technically, you could inspect the stack, but you really DONT want to go into such kind of dirty hacks. If you need specific "per view" behaviour, do it in the views (or in functions explicitely called by the views if you need to factor out this behaviour).

Also and FWIW, the point of signals is to allow for decoupling between apps - more specifically, to allow your app to hook into other apps (3rd part mostly) without having to touch those other apps code. Having signal handlers for models of your own app is an antipattern.

Upvotes: 3

Related Questions