我有一些自定义管理代码,用于初始化一些内联子对象。
如果用户编辑其中一个内联子对象的默认值,则在保存父对象时会创建该子元素。
我假设Django正在检查值是否已从initial
值更改,并且只有在用户更改了值时才会保存。
是这样的吗?
如果用户选择不更改默认值,如何强制Django Admin使用未更改的默认值创建内联子对象?
class PrepopIpInlineFormSet(forms.models.BaseInlineFormSet):
model = Ip
def __init__(self, *args, **kwargs):
super(PrepopIpInlineFormSet, self).__init__(*args, **kwargs)
initial = # calculate a set of default Ip model initial values
self.initial = initial
class PrepopIpInline(admin.options.InlineModelAdmin):
template = "admin/linked.html"
model = Ip
formset = PrepopIpInlineFormSet
fk_name = 'sim'
admin_model_path = None
show_url = True
def __init__(self, *args):
super(PrepopIpInline, self).__init__(*args)
if self.admin_model_path is None:
self.admin_model_path = self.model.__name__.lower()
def get_formset(self, request, obj=None, **kwargs):
formset = super(PrepopIpInline, self).get_formset(request, obj, **kwargs)
formset.request = request
return formset
def get_extra(self, request, obj=None, **kwargs):
if obj:
return 0
else:
return ApnGgsn.objects.all().count()
答案 0 :(得分:12)
原产地: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
答案 1 :(得分:0)
在ModelAdmin对象本身中,您可以超级save_related方法。然后,一旦完成,检查这些模型的存在。如果它们不存在,请创建它们。它看起来像这样:
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, ...)
完全公开:我不记得(在新创建的ParentObject的情况下)是否还会填充form.instance属性。我知道底层对象将在那时创建(因为save_model在save_related之前被调用)。
如果我提议的“obj = form.instance”不起作用,您也可以通过基于表单数据中的唯一值查询来获取该新对象。
例如,代替obj = form.instance,执行:
obj = ParentObject.objects.get(username = form.cleaned_data.get("username"))