问题
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 wich would be populated via java-script when adding a new inline. As this feels very hackish i hope there is a more elegant solution.
Any ideas would be greatly appreciated.
Thanks, Daniel.
回答1:
It took me quite some time to figure out but it is actually really simple.
from django.contrib import admin
from django.forms.models import BaseInlineFormSet, ModelForm
class AlwaysChangedModelForm(ModelForm):
def has_changed(self):
""" Should returns True if data differs from initial.
By always returning true even unchanged inlines will get validated and saved."""
return True
class CheckerInline(admin.StackedInline):
""" Base class for checker inlines """
extra = 0
form = AlwaysChangedModelForm
回答2:
@daniel answer is great, however it will try to save the instance that is already created ever if no changes is made, which is not necessary, better to use it like:
class AlwaysChangedModelForm(ModelForm):
def has_changed(self, *args, **kwargs):
if self.instance.pk is None:
return True
return super(AlwaysChangedModelForm, self).has_changed(*args, **kwargs)
来源:https://stackoverflow.com/questions/3657709/how-to-force-save-an-empty-unchanged-django-admin-inline