Generic Views (Django)

Generic views are Django's prebuilt class-based views for common tasks: listing objects, showing detail, and creating, updating, or deleting via forms. They handle the boilerplate so you only declare the model and a few options.

Django

Most views fall into a handful of patterns, and generic views implement them for you. ListView and DetailView cover read pages; CreateView, UpdateView, and DeleteView cover form-driven editing using a ModelForm under the hood; TemplateView renders a static template.

You subclass the appropriate generic view and set a few attributes — model, template_name, fields (for editing views), and context_object_name — and Django supplies the querying, form handling, and rendering. This can shrink a create-edit-delete CRUD interface to a few dozen lines.

Customize by overriding methods like get_queryset() (to filter what is shown) or get_context_data() (to add extra template variables). When a view's needs diverge far from the pattern, drop back to a plain function or View for clarity.

Syntax

class PostList(ListView):
    model = Post

Examples

Python

from django.views.generic import CreateView
from .models import Post

class PostCreate(CreateView):
    model = Post
    fields = ["title", "body"]
    template_name = "post_form.html"
    success_url = "/posts/"

# urls: path("new/", PostCreate.as_view())

Learn it in a lesson

See also

Back to the Dictionary