Django - init对象没有属性' kwargs'

时间:2018-02-05 10:13:31

标签: python django

我正在尝试过滤表单外键,如此帖set variable into queryset of forms.py from my generic view or url

但是我收到了错误

'AddSubnet' object has no attribute 'kwargs'

当我删除def init 功能时,问题就解决了。所以我知道它肯定与这个功能有关,但我不确定是什么。

完整追踪:

Traceback:

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view
  62.             self = cls(**initkwargs)

File "/itapp/itapp/sites/views.py" in __init__
  1001.         site_id = self.kwargs['site_id']

Exception Type: AttributeError at /sites/site/add_subnet/7
Exception Value: 'AddSubnet' object has no attribute 'kwargs'

views.py:

class AddSubnet(CreateView):
    model = SiteSubnets
    template_name = "sites/edit_subnet.html"
    fields = ['device_data', 'subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc']
    exclude = ['site_data'] 

    @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.kwargs['site_id'],))

    def __init__(self, *args, **kwargs):
        #site_id = kwargs.pop('site_id')
        site_id = self.kwargs['site_id']
        self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id)

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super(AddSubnet, self).get_form_kwargs()
        if kwargs['instance'] is None:
            kwargs['instance'] = SiteSubnets()
            kwargs['instance'].site_data = site = get_object_or_404(SiteData, pk=self.kwargs['site_id'])
            kwargs['site_id'] = self.kwargs['site_id']
        return kwargs

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

        return context

编辑:

我的表单现在看起来像这样

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

    def __init__(self, *args, **kwargs):
        site_id = self.kwargs.pop('site_id', None)
        super(AddSubnetForm, self).__init__(*arg)
        self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id)

我的观点是这样的:

class AddSubnet(CreateView):
    form_class = AddSubnetForm
    template_name = "sites/edit_subnet.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.kwargs['site_id'],))

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super(AddSubnet, self).get_form_kwargs()
        if kwargs['instance'] is None:
            kwargs['instance'] = SiteSubnets()
            kwargs['instance'].site_data = site = get_object_or_404(SiteData, pk=self.kwargs['site_id'])
            kwargs['site_id'] = self.kwargs['site_id']
        return kwargs

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

        return context

我收到了相同的错误,但现在在forms.py中

File "/itapp/itapp/sites/forms.py" in __init__
  199.         site_id = self.kwargs.pop('site_id', None)

Exception Type: AttributeError at /sites/site/add_subnet/7
Exception Value: 'AddSubnetForm' object has no attribute 'kwargs'

2 个答案:

答案 0 :(得分:1)

您尚未定义self.kwargs因此它不存在

self.site_id = self.kwargs['site_id']

应该是

self.site_id = kwargs['site_id']

答案 1 :(得分:1)

您永远不应该在视图上覆盖__init__方法。

但是看看你的代码,你似乎真的想把这个 - 和fields属性 - 放在表单上,​​而不是视图上。

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

    def __init__(self, *args, **kwargs):
        site_id = kwargs.pop('site_id', None)
        super(AddSubnetForm, self).__init__(*arg
        self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id)

class AddSubnet(CreateView):
    form_class = AddSubnetForm

(请注意,这是Alasdair在链接答案中所做的。)