How to force-save an "empty"/unchanged django admin inline?

Viewed 4586

I have some inlines in one of my admin models which have default values which likely won't need to be changed when adding a new instance with "Add another ...". Unfortunately django won't recognize these inline as new objects unless some value has changed. This forces me to add an inline, change an arbitrary value, save, change the value back and save again to reach the desired effect.

The only solution I've come up with so far is to add a hidden 'changed'-field which would be populated via JavaScript when adding a new inline. As this feels very hackish I hope there is a more elegant solution.

3 Answers

Combined @Daniels, @HardQuestions' and @jonespm answers:

class MarkNewInstancesAsChangedModelForm(forms.ModelForm):
    def has_changed(self):
        """Returns True for new instances, calls super() for ones that exist in db.
        Prevents forms with defaults being recognized as empty/unchanged."""
        return not self.instance.pk or super().has_changed()
Related