ListView

Display a list of objects with almost no code.

Syntaxclass PostListView(ListView): model = Post

ListView fetches a queryset and renders it to a template. Set the model (or queryset) and Django provides the object list as object_list in the context.

By default it looks for a template named <app>/<model>_list.html.

Example

Example · python
from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = "blog/post_list.html"
    context_object_name = "posts"
    paginate_by = 10

    def get_queryset(self):
        return Post.objects.filter(published=True)

When to use it

  • A developer uses ListView to display a paginated list of all published blog posts with minimal code.
  • A team overrides get_queryset() in a ListView to filter the list to the logged-in user's own objects.
  • A developer uses context_object_name to give the template a descriptive variable name like 'posts' instead of 'object_list'.

More examples

Basic ListView

Displays a paginated list of Post objects; template accesses them via the 'posts' variable.

Example · python
from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = "blog/post_list.html"
    context_object_name = "posts"
    paginate_by = 10

Filter queryset in ListView

Overrides get_queryset() to restrict the list to published posts ordered newest first.

Example · python
class PublishedPostListView(ListView):
    model = Post
    template_name = "blog/post_list.html"
    context_object_name = "posts"

    def get_queryset(self):
        return Post.objects.filter(draft=False).order_by("-published_at")

Add extra context

Extends get_context_data() to inject extra data alongside the default object list.

Example · python
class PostListView(ListView):
    model = Post
    template_name = "blog/post_list.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["total_count"] = Post.objects.count()
        return context

Discussion

  • Be the first to comment on this lesson.