gpt4 book ai didi

django - 如何在 Django 中将 InlineFormSet 放入 ModelFormSet 中?

转载 作者:行者123 更新时间:2023-12-02 07:04:52 24 4
gpt4 key购买 nike

我想通过 ModelFormSet 显示多个表单,其中每个表单依次显示连接到该对象的所有对象的 InlineFormSets

现在我不太确定如何为每个 ModelFormSet 提供实例。我考虑过对 BaseModelFormSet 进行子类化,但我不知道从哪里开始,并且想在经历所有麻烦之前知道这是否可行。

提前致谢!

最佳答案

我找到了一篇文章,重点讨论了确切的问题。效果很好!

http://yergler.net/blog/2009/09/27/nested-formsets-with-django/

为了完整起见,我复制了代码片段:

class Block(models.Model):
description = models.CharField(max_length=255)

class Building(models.Model):
block = models.ForeignKey(Block)
address = models.CharField(max_length=255)

class Tenant(models.Model):
building = models.ForeignKey(Building)
name = models.CharField(max_length=255)
unit = models.CharField(max_length=255)

form django.forms.models import inlineformset_factory, BaseInlineFormSet

TenantFormset = inlineformset_factory(models.Building, models.Tenant, extra=1)

class BaseBuildingFormset(BaseInlineFormSet):

def add_fields(self, form, index):
# allow the super class to create the fields as usual
super(BaseBuildingFormset, self).add_fields(form, index)

# created the nested formset
try:
instance = self.get_queryset()[index]
pk_value = instance.pk
except IndexError:
instance=None
pk_value = hash(form.prefix)

# store the formset in the .nested property
form.nested = [
TenantFormset(data=self.data,
instance = instance,
prefix = 'TENANTS_%s' % pk_value)]

BuildingFormset = inlineformset_factory(models.Block, models.Building, formset=BaseBuildingFormset, extra=1)

关于django - 如何在 Django 中将 InlineFormSet 放入 ModelFormSet 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1852475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com