So I have two models (Tables) related by a ForeignKey. In the admin, the edit page displays the first model (let's say ModelOne) along with the related instances of the second model, ModelTwo (TabularInline).
What I want is perform some additional actions when the second model is being changed. I can do this with a post_save signal on ModelTwo. However, the post_save signal is only called when I save the model from within its own edit page (ie. not within ModelOne's inlines).
Is there a way to attach a post_save signal on ModelTwo's inline form?
...As a workaround I added some custom validation to ModelTwo, which is being called regardless if it's inline or not), to call the method I want. However, the problem that arises from this setting is that if am creating a new instance of ModelOne and also create instances of ModelTwo at the same time I cannot access the primary key (foreign key) of the new instance that relates the two tables (since it has not been saved yet). And the primary key is something I need.
I also tried adding a post_save signal to ModelOne directly (so that I can get the new instance's PK) but it seems that the post_save signal does not pass ModelTwo's data (and why should it, anyway?)
So what's the solution to this? Do inline models emit signals? Is there a way to access the PK of the new instance before saving it?
Django includes a “signal dispatcher” which helps decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place.
django-inline-actions adds actions to each row of the ModelAdmin or InlineModelAdmin.
There are 3 types of signal. pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model's instance (method delete()) this signal is thrown.
Models are Models. The fact that a Model is used in the admin interface as inline doesn't take away from it in any way. All models emit a post save signal unless you override its functionality.
Here is what happens when you save any model.
Most of the time when a solution appeared to be solved with a signal, it ended up being solve better by overriding one of the various save methods. I have had a lot of success at injecting additional code at save time by overriding one of two methods:
Signals are still handy, but I've just had better luck at those two locations.
all the above are correct, just adding on more thing: when you save an object in admin (that contain inline), the 'post-save' signal of the inline (and of course the save method of the inline object) are triggered only if you made some changes to the inline object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With