mrchestnut
mrchestnut

Reputation: 472

Django: Class-based views, URL and template_name

I am trying to use something like polls:detailin a class-based view, such as this:

class QuestionDetail(DetailView):
    template_name = 'polls:result'

However, I get a TemplateDoesNotExist at /polls/2/result polls:result error...

The urls.py is:

from django.conf.urls import url
from polls.views import IndexView, DetailView, ResultsView

from . import views


app_name = 'polls'
urlpatterns = [
    url(r'^$', IndexView.as_view(), name='index'),
    url(r'^(?P<pk>\d+)/$', DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>\d+)/result$', ResultsView.as_view(), name='result'),
    url(r'^(?P<pk>\d+)/vote$', views.vote, name='vote'),
]


I guess the main question is, how do I use the names of URLs in class-based views, instead of explicitly providing the template name, such as polls/question_results.html?

Is there anything other than template_name?

I was reading that it's a good practice to use names in URLS so in case the URL itself changes, the rest of the code still works, so that's what I'm trying to do.

Upvotes: 2

Views: 4616

Answers (2)

Vadym
Vadym

Reputation: 1555

Url name and template name are very absolutely things.

template_name is a path to the .html file.

Url's name parameter you can use to reverse url from name using django.urls.reverse

Upvotes: 1

Dat TT
Dat TT

Reputation: 3083

You can use the name of URL like this: django.urls.reverse('polls:detail', args=[object.id])

And you have to change the template_name settings as well and to create a template detail.html in your current template folder.

template_name = 'polls/detail.html'

Upvotes: 1

Related Questions