我想使用嵌入式内联formset,使用django-extra-views进行创建和更新。
我可以毫无问题地实现典型的(非嵌套的)内联formset。这是一个基本的例子。
# forms.py
class ProductForm(forms.ModelForm):
class Meta:
model = models.Product
# for brevity, assume these fields are defined on the `Product` model
fields = [
'name',
'image',
'price',
]
class VariantForm(forms.ModelForm):
class Meta:
model = models.Variant
# for brevity, assume these fields are defined on the `Variant` model
fields = [
'price_override',
'shipping_dimensions',
]
class InlineVariant(InlineFormSet):
model = models.Variant
form_class = VariantForm
extra = 1
和
# views.py
class Add(CreateWithInlinesView):
template_name = "products/add.html"
model = models.Product
form_class = forms.ProductForm
inlines = [
forms.InlineVariant,
]
class Edit(UpdateWithInlinesView):
template_name = "products/edit.html"
model = models.Product
form_class = forms.ProductForm
context_object_name = "product"
inlines = [
forms.InlineVariant,
]
但是,现在我希望Stock
为每个Variant
内联。
# forms.py
class StockForm(forms.ModelForm):
class Meta:
model = models.Stock
# for brevity, assume these fields are defined on the `Stock` model
fields = [
'location',
'quantity',
]
class InlineStock(InlineFormSet):
model = models.Stock
form_class = StockForm
extra = 1
如何修改上面定义的视图?
现有的django-extra-views issue断言这是可能的。但是,没有明确的例子说明如何做到这一点。有人建议制作自定义formset_class
。
我还找到了一个单独的包django-nested-admin,它定义了一个看似通用的NestedInlineFormset
类。可以以某种方式整合吗?
我发现这真令人困惑。