0

如何将DetailView传递给 url 中的“slug”?

首先,让我们看看我的代码。

网址.py

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
    url(r'^customer/(?P<slug>[^/]+)/$', customerDetailView.as_view()),
)

视图.py

from django.views.generic import DetailView

class customerDetailView(DetailView):
    context_object_name = 'customerDetail'
    template_name = "customerDetail.html"
    allow_empty = True
    model = Customer
    slug_field = 'name' # 'name' is field of Customer Model

现在,我的代码就像上面一样。

我想更改如下代码。

网址.py

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
    url(r'^customer/(?P<slug>[^/]+)/$', customer),
)

视图.py

from django.views.generic import DetailView

class customerDetailView(DetailView):
    context_object_name = 'customerDetail'
    template_name = "customerDetail.html"
    allow_empty = True
    model = Customer
    slug_field = 'name' # 'name' is field of Customer Model

def customer(request, slug):
    if request.method == "DELETE":
        pass # some code blah blah
    elif request.method == "POST"
        pass
    elif request.method == "GET":
        return customerDetailView.as_view(slug=slug)(request) # But this line is not working... just causing error TypeError, customerDetailView() received an invalid keyword 'slug'

如您所知,DetailView 需要“slug”或“pk”...所以我必须将“slug”交付给 DetailView...但我不知道如何交付“slug”...

我在显示器前等你的答案...

谢谢!

4

1 回答 1

4

正确的方法应该是

return customerDetailView.as_view()(request, slug=slug)
于 2013-04-11T02:40:00.940 回答