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

I have a set of questions in the database. I want to display each question in a collapsible item as a list. I used to use 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 best practice for presenting 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 a loop:

 {% for question in questions %} 

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

I really do not see such a big difference between using TemplateView and ListView - spending an hour on this. I would appreciate someone explaining why using ListView instead of TemplateView is best practice (in this case).

Thanks in advance.

+5
source share
1 answer

For simple use cases like this, there is not much difference. However, the ListView in this example is much cleaner since it can be reduced to:

 class QuestionListView(ListView): model = Question 

given that you don’t put anything into context. TemplateView's as a base view is rather rudimentary and provides a much smaller set of methods and attributes to work in more complex use cases, that is, you need to write more code in such cases. If you look and compare both the TemplateView and ListView, here you can see the difference more clearly. Pagination is a good example, for pagination ListView you simply set the paginate_by attribute and modify your template accordingly.

Also note: you can change the default name of object_list by setting context_object_name to "ListView"

+2
source

Source: https://habr.com/ru/post/1200455/


All Articles