我有一个modelformset AddressFormSet = modelformset_factory(Address)
。在我看来,我将此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)
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
如何为它们指定不同的名称,以便两个formset中的数据都能创建对象。
答案 0 :(得分: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