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

Posted

技术标签:

【中文标题】如何将 DetailView 传递给 url 中的“slug”?【英文标题】:How to pass DetailView over the 'slug' in url? 【发布时间】:2013-04-03 02:30:00 【问题描述】:

如何将DetailView 传递给 url 中的“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”...

我在监视器前等待你的回答...

谢谢!

【问题讨论】:

【参考方案1】:

正确的方法应该是

return customerDetailView.as_view()(request, slug=slug)

【讨论】:

以上是关于如何将 DetailView 传递给 url 中的“slug”?的主要内容,如果未能解决你的问题,请参考以下文章

将 Pk 或 Slug 传递给 Django 中的通用 DetailView?

SwiftUI 和 CoreData:将 FetchResults 传递给 DetailView 并更新它们

将数据从 plist 传递到 DetailView

如何将点击的卡片按钮 id 传递给 vue.js 中的后端 URL 路径?

如何获取url中的参数并传递给iframe中的报表

如何使用当前登录用户作为 Django DetailView 的 PK?