窗口小部件属性不起作用

时间:2018-01-06 12:58:07

标签: django django-forms django-templates django-views

我有两个表单和一个formset。我已经为这两个表单提供了__init__。但是在我的模板中,只有我的POBodyForm使用属性进行渲染。看起来POHeaderForm的__init__无效。我不确定是什么错误。有人可以建议吗?

我一直在我的项目中使用类似的__init__类,这是表单第一次拒绝呈现或导致我出现问题。 enter image description here 相关表格代码:

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)

1 个答案:

答案 0 :(得分:0)

我无法弄清楚这个的确切原因。我认为我的问题是视图,我的观点由于某种原因覆盖了init方法。我从基于类的视图转移到基于函数的视图,它运行得很好。这不是一个确切的解决方案,但可以使用备用选项。正如我的工作一样。

enter image description here