Dynamic initial value when adding another inline form with the 'Add another' button

Here is a short description of my situation:

  • I have a Contract model and an Annex model that has a foreign key to the Contract model;
  • In admin.py, I’ve configured a StackedInline form for the Annex so that I can create annexes from the creation form of a Contract;
  • The Annex model has an attribute (reference) that I want to prepopulate. The value should be ‘a’ for the first inline form, ‘b’ for second, ‘c’ for the third, etc. I was able to implement this feature by adding a specific ModelForm for the StackedInline form, and by surcharging the get_initial_for_field method;

And here is my problem: when I click on the “Add another Annex” in the bottom of the stacked inline forms, I don’t get a proper value for the reference field. This is working well for a static value (so each reference field value is ‘a’, but not for a dynamic value (reference field of the first form get ‘a’, the one of the second form get ‘b’, etc.).

Is it possible to do something like that in Django Admin? And if so, what would be the proper way?

Thanks in advance!

The work done by the “Add another …” link in an inline is handled solely by the JavaScript in that page. No request is initiated by the browser for the addition of a new form.

Therefore, doing this would require changes to (or overrides for) functions in the inlines.js file.

Thank you for your answer! I’ll check how I can add this feature.