gpt4 book ai didi

python - Django:如何在 gereric DetailView 中使用自定义 slug(必须使用对象 pk 或 slug 调用通用详细 View DetailView)

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:36 26 4
gpt4 key购买 nike

I am newbie on python django. when following Django Tutorial > Part04 > Generic View , i have trouble with using Detail View. and actually its my first question on StackOverflow, so if i am wrong with something, please let me know. Thanks very much.

我想要什么?

  • 我想url(r'^(?P<question_id>\d+)/$', views.DetailView.as_view(), name="detail")优于url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name="detail") .因为它更具可读性和直观性。
  • 所以我不想改变polls/urls.py .
  • 我如何使用详细 View ,但仍保留 <CUSTOM_SLUG>views.py

源代码

django_project/polls/urls.py (目前不工作)

urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name="index"),
url(r'^(?P<question_id>\d+)/$', views.DetailView.as_view(), name="detail"),
url(r'^(?P<question_id>\d+)/results/$', views.results, name="results"),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name="vote"),
)

django_project/polls/urls.py (工作来源,但我不想要这个。)

urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name="index"),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name="detail"),
url(r'^(?P<question_id>\d+)/results/$', views.results, name="results"),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name="vote"),
)

django_project/polls/views.py

class DetailView(generic.DetailView):
model = Question
template_name = "polls/detail.html"

错误信息

通用详细 View DetailView 必须使用对象 pk 或 slug 调用。

最佳答案

https://docs.djangoproject.com/en/1.6/intro/tutorial04/

The DetailView generic view expects the primary key value captured from the URL to be called "pk", so we’ve changed poll_id to pk for the generic views.

所以这显然行不通:

url(r'^(?P<question_id>\d+)/$', views.DetailView.as_view(), name="detail"),

而这将起作用:

url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name="detail"),

子类化 DetailView 以使用不同的正则表达式组名称:

https://github.com/django/django/blob/master/django/views/generic/detail.py

但是如果你将 DetailView 子类化,你可以告诉它什么是 pk 参数:

class MyCustomDetailView(DetailView):
pk_url_kwarg = 'object_id'

pk 是django中的标准术语;虽然这可能会使您的代码对您来说更具可读性,其他对 django 感到满意的人可能认为 pk 更具可读性。如果您想自定义所有小细节,使用通用 View 有什么意义?

关于python - Django:如何在 gereric DetailView 中使用自定义 slug(必须使用对象 pk 或 slug 调用通用详细 View DetailView),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24967397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com