Reputation: 49
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")
is better than url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name="detail")
. because its more readable and intuitive.polls/urls.py
.<CUSTOM_SLUG>
on views.py
django_project/polls/urls.py
( currently not working )
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
( working source, but i don't want this. )
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"
Generic detail view DetailView must be called with either an object pk or a slug.
Upvotes: 2
Views: 1138
Reputation: 24324
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.
so this will obviously not work:
url(r'^(?P<question_id>\d+)/$', views.DetailView.as_view(), name="detail"),
whereas this will work:
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name="detail"),
DetailView
to use a different regex group name:https://github.com/django/django/blob/master/django/views/generic/detail.py
But if you subclass DetailView
you can tell it what is the pk
parameter:
class MyCustomDetailView(DetailView):
pk_url_kwarg = 'object_id'
pk
is a standard term in django; while this may make your code more readable to you,
anybody else comfortable with django may think pk
is more readable. What is the point of using a generic
view if you want to customize all the small details?
Upvotes: 2