如何将DetailView传递给网址中的'slug'?
首先,让我们看看我的代码。
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^customer/(?P<slug>[^/]+)/$', customerDetailView.as_view()),
)
views.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
现在,我的代码就像上面一样。
我想改变下面的代码。
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^customer/(?P<slug>[^/]+)/$', customer),
)
views.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'......
我正等着你的回答... ...
谢谢!
答案 0 :(得分:4)
正确的方法应该是
return customerDetailView.as_view()(request, slug=slug)