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'......
我该怎么办?
答案 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_field
和slug_url_kwarg
。