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.
Generally, Detail is for 1 item, List is for many.
TemplateView should be used when you want to present some information in a html page. TemplateView shouldn't be used when your page has forms and does creation or update of objects. In such cases FormView, CreateView or UpdateView is a better option.
ListView. A page representing a list of objects. While this view is executing, self. object_list will contain the list of objects (usually, but not necessarily a queryset) that the view is operating upon.
A TemplateView is a generic class-based view that helps developers create a view for a specific template without re-inventing the wheel. TemplateView is the simplest one of many generic views provided by Django. You can create a view for an example index.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With