我有两个表单和一个formset。我已经为这两个表单提供了__init__
。但是在我的模板中,只有我的POBodyForm使用属性进行渲染。看起来POHeaderForm的__init__
无效。我不确定是什么错误。有人可以建议吗?
我一直在我的项目中使用类似的__init__
类,这是表单第一次拒绝呈现或导致我出现问题。
相关表格代码:
class POHeaderForm(forms.ModelForm):
class Meta:
model = POHeaderModel
fields = '__all__'
def __init__(self, *args, **kwargs):
super(POHeaderForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs = {'class': 'form-control form-control-sm'}
class POBodyForm(forms.ModelForm):
class Meta:
model = POBodyModel
fields = '__all__'
def __init__(self, *args, **kwargs):
super(POBodyForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs = {'class': 'form-control form-control-sm'}
POFormSet = forms.inlineformset_factory(POHeaderModel, POBodyModel,form=POBodyForm, extra=1)
,视图如下:
class PurchaseOrderCBV(CreateView):
model = POHeaderModel
fields = '__all__'
success_url = reverse_lazy('purchase_order')
def get_context_data(self, **kwargs):
data = super(PurchaseOrderCBV, self).get_context_data(**kwargs)
if self.request.POST:
data['formbody'] = POFormSet(self.request.POST)
else:
data['formbody'] = POFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
formbody = context['formbody']
with transaction.atomic():
self.object = form.save()
if formbody.is_valid():
formbody.instance = self.object
formbody.save()
return super(PurchaseOrderCBV, self).form_valid(form)