What is the difference between using TemplateView and ListView in Django?

Issue

In the database, I have a set of questions. I want to display every question in a collapsible item as a list. Previously I used TemplateView:

class questionmanager(TemplateView):
    template_name = 'questionmanager.html'
    questions = Question.objects.all() 

    def get_context_data(self, **kwargs):
        context = ({
            'questions': self.questions,
        })
        return context  

Then, I read that using ListView is better practice to represent a list of objects. Then I changed my class to this:

class QuestionListView(ListView):
    model = Question

    def get_context_data(self, **kwargs):
        context = super(QuestionListView, self).get_context_data(**kwargs)
        return context

In the old template I used this for loop:

{% for question in questions %}

I thought I wouldn’t need to use a for loop when I use ListView instead of TemplateView; but I couldn’t list the items without a for loop. I found an example here, and it seems to me, the only difference is that in the for loop we use object_list ( {% for question in **object_list** %}) instead of using argument that we pass in the context.

I really don’t see so much difference between using TemplateView and ListView – after spending an hour on this. I’d appreciate if someone explains why using ListView instead of TemplateView is a better practice (in this case).

Thanks in advance.

Solution

For simple use cases such as this, there isn’t much difference. However, the ListView in this example is much cleaner as it can be reduced to:

class QuestionListView(ListView):
    model = Question

considering you aren’t putting anything in the context. TemplateView's as a base view are rather rudimentary, and provide a much smaller set of methods and attributes to work with for the more complex use cases, meaning you have to write more code in such instances. If you take a look and compare both views TemplateView and ListView here, you can see the difference more clearly. Pagination is a good example, to paginate a ListView you simply set the paginate_by attribute and modify your template accordingly.

Also note, you can change the default name object_list by setting context_object_name in the ‘ListView’

Answered By – crhodes

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published