Question

How to pass DetailView over the 'slug' in url?

First, let's look at my code.

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

Now, my code is like above.

And I want to change code like below.

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'

As you know, DetailView need to 'slug' or 'pk'... So I must deliver 'slug' over to the DetailView... But I don't know how do I deliver 'slug'...

I'm waiting your answer front of moniter...

Thank you!

Was it helpful?

Solution

The correct way should be

return customerDetailView.as_view()(request, slug=slug)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top