1

我有一个 modelformset AddressFormSet = modelformset_factory(Address)。在我看来,我将此表单集分配给不同的上下文变量,但它们似乎是重复的。输入名称相同。

def get_context_data(self, **kwargs):
    context = super(TravelCreate, self).get_context_data(**kwargs)
    if self.request.POST:
        context['address1'] = AddressFormSet(self.request.POST)
        context['address2'] = AddressFormSet(self.request.POST)
    else:
        context['address1'] = AddressFormSet(queryset=self.model.objects.none())
        context['address2'] = AddressFormSet(queryset=self.model.objects.none())
    return context

如何给它们不同的名称,以便来自两个表单集的数据创建对象。

4

1 回答 1

1

从工厂创建它们时,您需要为这两个 Formset 提供不同的前缀,否则它们都将使用来自发布数据的相同名称

def get_context_data(self, **kwargs):
    context = super(TravelCreate, self).get_context_data(**kwargs)
    if self.request.POST:
        context['address1'] = AddressFormSet(self.request.POST, prefix='address1')
        context['address2'] = AddressFormSet(self.request.POST, prefix='address2')
    else:
        context['address1'] = AddressFormSet(queryset=self.model.objects.none(), prefix='address1')
        context['address2'] = AddressFormSet(queryset=self.model.objects.none(), prefix='address2')
    return context

参考:https ://docs.djangoproject.com/en/1.5/topics/forms/formsets/#using-more-than-one-formset-in-a-view

于 2013-04-30T08:42:30.267 回答