简体   繁体   English

Django Update和CreateView使用相同的Crispy Form,添加视图错误

[英]Django Update and CreateView using the same Crispy Form, Add view Error

I'm using the same crispy form for add and edit and have added a variable to so I can change the submit button text from add to edit and vice versa. 我使用相同的crispy形式进行添加和编辑,并添加了一个变量,因此我可以将提交按钮文本从添加更改为编辑,反之亦然。

However the add view is coming up with the below error: 但是添加视图会出现以下错误:

Traceback: (removed the in built references) 

...

File "/itapp/itapp/sites/views.py" in dispatch
  954.         return super(AddSubnet, self).dispatch(*args, **kwargs)

...

File "/itapp/itapp/sites/views.py" in get_context_data
  969.         context = super().get_context_data(**kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get_context_data
  93.             kwargs['form'] = self.get_form()

File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get_form
  45.         return form_class(**self.get_form_kwargs())

Exception Type: TypeError at /sites/site/add_subnet/7
Exception Value: 'SubnetForm' object is not callable

im not sure as to why as the code for the form looks good to my unskilled eyes at least anyway 我不确定为什么因为表格的代码至少无论如何对我不熟练的眼睛看起来都很好

forms.py: forms.py:

class SubnetForm(forms.ModelForm):
    class Meta:
        model = SiteSubnets
        fields = ['subnet', 'subnet_type', 'circuit', 'device_data', 'vlan_id', 'peer_desc']

    def __init__(self, *args, **kwargs):
        site_id = kwargs.pop('site_id', None)
        self.is_add = kwargs.pop("is_add", False)
        super(SubnetForm, self).__init__(*args, **kwargs)
        self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id)
        self.helper = FormHelper(self)
        self.helper.form_id = 'subnet_form'
        self.helper.form_method = 'POST'
        self.helper.add_input(Submit('submit', 'Add Subnet' if self.is_add else 'Edit Subnet', css_class='btn-primary'))
        self.helper.layout = Layout(
            Div(    
                Div(
                    Field('subnet', placeholder='Subnet'),
                    Div('subnet_type', title="Subnet Type"),
                    css_class='col-lg-3'
                ),
                Div(
                    Div('circuit', title='Circuit'),
                    Div('device_data', title="Device Data"),
                    css_class='col-lg-3'
                ),
                Div(
                    Field('vlan_id', placeholder='VLAN ID'),
                    Field('peer_desc', placeholder="Peer Description"),
                    css_class='col-lg-3'
                ),
            css_class='row'
            )
        )

Views: 浏览次数:

class AddSubnet(CreateView):
    form_class = SubnetForm(is_add=True)
    template_name = "sites/subnet_form.html"

    @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet')))
    def dispatch(self, *args, **kwargs):
        self.site_id = self.kwargs['site_id']
        self.site = get_object_or_404(SiteData, pk=self.site_id) 
        return super(AddSubnet, self).dispatch(*args, **kwargs)

    def get_success_url(self, **kwargs):         
            return reverse_lazy("sites:site_detail_subnets", args=(self.site_id,))

    def form_valid(self, form):
        form.instance.site_data = self.site
        return super(AddSubnet, self).form_valid(form)

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super().get_form_kwargs()
        kwargs['site_id'] = self.site_id
        return kwargs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['SiteID']=self.site_id
        context['SiteName']=self.site.location
        context['FormType']='Add'
        context['active_subnets']='class="active"'

        return context

class EditSubnet(UpdateView):
    model = SiteSubnets
    form_class = SubnetForm
    template_name = "sites/subnet_form.html"

    @method_decorator(user_passes_test(lambda u: u.has_perm('config.edit_subnet')))
    def dispatch(self, *args, **kwargs):
        self.site_id = self.kwargs['site_id']
        self.site = get_object_or_404(SiteData, pk=self.site_id) 
        return super(EditSubnet, self).dispatch(*args, **kwargs)

    def get_success_url(self, **kwargs):         
            return reverse_lazy("sites:site_detail_subnets", args=(self.site_id,))

    def form_valid(self, form):
        form.instance.site_data = self.object.site_data
        return super(EditSubnet, self).form_valid(form)

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super().get_form_kwargs()
        return kwargs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['SiteID']=self.site_id
        context['SiteName']=self.site.location
        context['FormType']='Edit'
        context['active_subnets']='class="active"'

        return context

This is the culprit: form_class = SubnetForm(is_add=True) . 这是罪魁祸首: form_class = SubnetForm(is_add=True) form_class is supposed to be what the name indicates, just the class , not an instance. form_class应该是名称所指示的,只是class ,而不是实例。 Use get_form_kwargs to add initialization parameters to the form constructor call (as you already do with site_id ): 使用get_form_kwargs将初始化参数添加到表单构造函数调用(就像您已经使用site_id ):

class AddSubnet(CreateView):
    form_class = SubnetForm   # just the form CLASS
    # ...

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super().get_form_kwargs()
        kwargs['is_add'] = True  # you can set 'is_add' here
        kwargs['site_id'] = self.site_id
        return kwargs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM