urls.pydjango:如何將變量傳遞給類?
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/',而是 '名' 是無...
如何獲得'姓名'? 我該怎麼辦?
編輯-----
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' ......
我該怎麼辦?
我已經更新瞭解決第二個問題的答案。 – 2013-02-09 12:52:55