1

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

我該怎麼辦?

+0

我已經更新瞭解決第二個問題的答案。 – 2013-02-09 12:52:55

回答

1

您應該可以通過self.kwargs['name']訪問該參數。此外,get_queryset應該返回一個查詢集。

你還需要使用pk,而不是name在您的網址,如果你想使用DetailView通用視圖。之後,您只需要在customerDetailView類中定義model = Customerslug_field = 'name',它應該可以工作。你根本不需要訪問self.kwargs['name'][source]

如果你真的想在你的URL中使用<name>,你也需要改變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

+0

謝謝...但mycode仍然打破... – chobo 2013-02-09 11:38:49

+0

我想要'pk'。所以'self.pk = Customer.objects.get(name = self.name).pk'< - 此代碼將__init__。但仍然破... – chobo 2013-02-09 11:39:38

+0

@chobo你現在得到什麼錯誤? – 2013-02-09 11:39:51