I have some custom admin code which initialises some inline child objects.
If the user edits one of the inline child object\'s default values, then that child elemen
Origin: How to force-save an "empty"/unchanged django admin inline?
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
In the ModelAdmin object itself, you could super the save_related method. Then, once that is completed, check for the existence of those models. If they don't exist, create them. It would look something like this:
class ParentObjectAdmin(admin.ModelAdmin):
def save_related(self, request, form, formsets, change):
super(ParentObjectAdmin, self).save_related(request, form, formsets, change)
obj = form.instance
if form.is_valid() and not ChildObject.objects.filter(parent = obj).exists():
ChildObject.objects.create(name = ChildObject.default_name, parent = obj, ...)
Full disclosure: I can't remember if (in the case of a newly created ParentObject) whether or not the form.instance attribute will yet be populated. I do know that the underlying object will have been created at that point (because save_model is called before save_related).
If what I'm proposing with "obj = form.instance" doesn't work, you can also get that new object by querying based on unique values in your form data.
For example, instead of obj = form.instance, do:
obj = ParentObject.objects.get(username = form.cleaned_data.get("username"))