Django CBV - 获取在类中使用的url变量,未定义错误自定义

时间:2018-01-30 15:24:13

标签: python django

我正在传递并尝试在我的添加表单中使用site_id。我想在网址中预先填写并隐藏site_data字段和网站ID。然后使用该变量将更多信息传递给上下文。

我的CBV是这样的:

class AddSubnet(CreateView):
    model = SiteSubnets
    template_name = "sites/edit_subnet.html"
    fields = ['device_data', 'site_data', 'subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc']
    site_id = self.kwargs['site_id']
    site = get_object_or_404(SiteData, pk=site_id) 

    @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet')))
    def dispatch(self, *args, **kwargs):
        return super(AddSubnet, self).dispatch(*args, **kwargs)

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

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['SiteID']=site_id
        context['SiteName']=site.location
        context['active_subnets']='class="active"'
        #
        return context

目前收益率为:

  File "/itapp/itapp/sites/urls.py", line 2, in <module>
    from . import views
  File "/itapp/itapp/sites/views.py", line 984, in <module>
    class AddSubnet(CreateView):
  File "/itapp/itapp/sites/views.py", line 988, in AddSubnet
    site_id = self.kwargs['site_id']
NameError: name 'self' is not defined

编辑:

url就是这样

url(r'^site/add_subnet/(?P<site_id>[0-9]+)$', views.AddSubnet.as_view(), name='add_subnet'),

2 个答案:

答案 0 :(得分:3)

class AddSubnet(CreateView):
    site_id = self.kwargs['site_id']
    site = get_object_or_404(SiteData, pk=site_id) 

您无法在类定义中像这样访问self。此代码在加载模块时运行。还没有请求,因此self.kwargs不存在。

您可以将代码移到调度方法中:

@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)

然后在其他方法中使用self.site_idself.site

答案 1 :(得分:0)

您写的语法无效。从代码中删除以下两行

site_id = self.kwargs['site_id']
site = get_object_or_404(SiteData, pk=site_id)

在方法get_context_data

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