1

网址.py

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

视图.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'...

如何接收“姓名”?我该怎么办?

编辑 - - -

视图.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'...

我该怎么办?

4

1 回答 1

1

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

如果要使用通用视图,还需要在 URL 中使用pk而不是。之后,您只需要在您的类中定义和,它应该可以工作。您根本不需要访问。[来源]nameDetailViewmodel = Customerslug_field = 'name'customerDetailViewself.kwargs['name']

如果你真的<name>在你的 URL 中使用,你还需要更改slug_url_kwargname(除了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在您的班级中。

于 2013-02-09T11:26:20.473 回答