[Fixed]-What is the difference between using TemplateView and ListView in Django?

11👍

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’

1👍

The major difference is that ListView is best to list items from a database called model, while TemplateView is best to render a template with no model. Both views can be very concise with different meaning.
Below is sample of a list view in it simplest form

Class SampleListView(ListView):
    model = ModelName

This will give you a context variable object_list and a template name in the form ("app_name/model_name_list.html") automatically that can be used to list all records in the database.

However, the TemplateView in its simplest form is

class SampleTemplateView(TemplateView):
    template_name = 'app_name/filename.html'

Leave a comment