what's the difference between TemplateView, ListView and DetailView ?

851 views
Skip to first unread message

Gear Crew

unread,
Sep 23, 2018, 9:47:17 AM9/23/18
to Django users
I want to know when I use  TemplateView , ListView and DetailView on my template code 

Mateusz

unread,
Sep 23, 2018, 1:02:17 PM9/23/18
to Django users
Django provides base view classes which will suit a wide range of applications. All views inherit from the View class, which handles linking the view in to the URLs, HTTP method dispatching and other simple features. RedirectView is for a simple HTTP redirect, and TemplateView extends the base class to make it also render a template.

TemplateView (docs)
Renders a given template, with the context containing parameters captured in the URL.
Use it when you want just to render some template, without getting objects from database. 

ListView (docs)
A page representing a list of objects.
Use it when you want to represent multiple objects from your database on a list (single template with multiple objects -- e.g. a list of products that are available in the shop or list of to-dos...).

DetailView (docs)
While this view is executing, self.object will contain the object that the view is operating upon.
Use it when you want to represent single object from your database (single template with one object, detailed -- e.g. product page).

Why to use DetailView and ListView instead of always using TemplateView?
Main reason is that using the views simplifies writing and reading the code. You can use built-in methods that do almost the whole job for you (actually they are used "automagically" and if you want them to do something else, e.g. add filtering to your ListView, you can just override them).

Mateusz

unread,
Sep 23, 2018, 1:43:28 PM9/23/18
to Django users
My answer was not fully on the topic. You shouldn't do what you want to do but if there's a real need for that...

You can add context by overriding get_context() method.

(context = super().get_context(); context['type'] = list; return context).

{% if type == list %}
<p>This is a list</p>
{% elif type == template %}
<p>This is just a template</p>
...

Or just e.g. context['list'] == True
And then:
{% if list %}
<p>This is a list</p>
{% if template %}
<p>This is just a template</p>
...

Reply all
Reply to author
Forward
0 new messages