Django Admin StackedInline save() overwrite

Hi,

I have a 1:n relationship of two models. I use the admin.StackedInline method to generate the form in the Django Admin.

My related model has a field position = models.PositiveSmallIntegerField(default=0) for ordering the related models. My idea was to keep it simple and allow my users to manually define the ordering number. But I also wanted new relations to be automatically sorted at the end. The idea was to overwrite the save() method and check if position == 0 and if so check the highest number for the childs of the parent model and just increment the found number and set on the new child model.

But overwriting the save() method does not work in context of the admin.StackedInline admin form.

My solution is now to handle the case via a pre_save signal for the child model. Which works, but also moves the logic “away” form the actual model code.

So my question is, if this a “okayisch” solution, or if there are alternatives which might be better suited to this problem?

Which save method did you try to override? The base model or the related model?

A StackedInline uses a formset. In the worst-case scenario, you could always override the default formset being used (BaseInlineFormSet). (This could include using your own form for the formset having that functionality built into it.)

Ah, I have overwritten the save() method of the related model.

I allow editing the related model also in it’s own primary admin form (where overwriting the save() method worked!).

Overwriting save methods on many different places would be not what I wan’t to do (hence the workaround via the signal thingy).

Figuring from you answer – if I only want to have one place to overwrite/change something – the signal seems the best place? I don’t want to overwrite something for the “stand alone form” and the StackedInline formset.

I never consider the use of Django signals as the “best” for anything. Django signals are my “choice of last resort”. I only use signals when I have no other practical choice - and if the alternative means I need to replicate code multiple times, I prefer replicating the code.

If you create a “stand alone form” doing what you need, then you could configure your StackedInline formset to use that form.

1 Like