django:如何将变量传递给类?

时间:2013-02-09 11:06:47

标签: django python-2.7 python-2.x django-generic-views django-1.4

urls.py

url(r'^customer/(?P<name>[^\s]+)/$', customerDetailView.as_view(), name="customerDetailView"), #pass 'name' variable

views.py

class customerDetailView(DetailView):
    context_object_name = 'customerDetail'
    template_name = "customer.html"
    allow_empty = True

    def __init__(self, name=None, *args):
        self.name = name # name is 'None'... Why...?

    def get_queryset(self):
        return Customer.objects.get(name=self.name)

我只是要求'192.168.1.5/customer/abc/',但'name'是没有......

如何收到'姓名'? 我该怎么办?

编辑-----

views.py

class customerDetailView(DetailView):
    context_object_name = 'customerDetail'
    template_name = "customer.html"
    allow_empty = True
    """
    def __init__(self, **kwargs):
        import pdb;pdb.set_trace()
        self.name = kwargs['name']
    """
    def get_queryset(self):
        # import pdb;pdb.set_trace()
        self.name = self.kwargs['name'] # Thanks  Kay Zhu!!
        return Customer.objects.get(name=self.name)

我申请你回答的代码。

然后,我收到错误

Generic detail view customerDetailView must be called with either an object pk or a slug.

所以我需要'pk'......

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您应该可以使用self.kwargs['name']访问参数。此外,get_queryset应该返回一个查询集。

如果您想使用pk通用视图,还需要在网址中使用name代替DetailView。之后,您只需要在model = Customer课程中定义slug_field = 'name'customerDetailView即可。您根本不需要访问self.kwargs['name'][source]

如果确实希望在您的网址中使用<name>,您还需要将slug_url_kwarg更改为name(除了slug_field = 'name'

class customerDetailView(DetailView):
    context_object_name = 'customerDetail'
    template_name = "customer.html"
    allow_empty = True
    model = Customer
    slug_field = 'name'
    slug_url_kwarg = 'name'
    # no need to override any methods here

或通过以下方式覆盖get_object

def get_object(self):
    return get_object_or_404(Customer, name=self.kwargs['name'])

无需修改班级中的slug_fieldslug_url_kwarg