Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 77 ยท URLs and Views

Generic Display and Editing Views

Build list, detail, create, update and delete pages with Django's generic class-based views. Customize get_queryset, get_context_data, success_url and pagination.

Look at almost any web application and you find the same five pages for every kind of data: a list, a detail page, a form to create one, a form to edit one and a confirmation page to delete one. Writing those by hand for each model is repetitive. Django's generic views are class-based views that already implement these five patterns. You name a model and Django does the querying, the 404 handling, the form processing and the redirect.

This lesson uses the views on a small Note model and runs them against an in-memory SQLite database. It builds on Class-Based Views, and it touches models and forms briefly; both get their own chapters later (Models and Fields, Django Forms).

The generic views at a glance

View Purpose Default template name Key attributes
ListView A page of many objects <app>/<model>_list.html model, queryset, paginate_by, ordering
DetailView One object by pk or slug <app>/<model>_detail.html model, slug_field, pk_url_kwarg
CreateView Form that saves a new object <app>/<model>_form.html fields or form_class, success_url
UpdateView Form that edits an object <app>/<model>_form.html same, plus the pk in the URL
DeleteView Confirmation, then delete <app>/<model>_confirm_delete.html success_url

For a Note model in an app called notes, the list template is notes/note_list.html. You can change any default with template_name.

flowchart LR
    U["URL with pk"] --> V["DetailView"]
    V --> Q["get_queryset()"]
    Q --> O["get_object()<br/>404 if missing"]
    O --> C["get_context_data()"]
    C --> T["render template"]

A generic view is a pipeline of small methods. Override the step you want to change and leave the rest alone.

ListView and DetailView

ListView needs a model (or a queryset). It puts the objects in the template as both object_list and <model>_list (here note_list). With paginate_by set, it also provides page_obj, paginator and is_paginated, and reads the page number from ?page=.

DetailView takes the pk captured by the URL (<int:pk>) and puts the object in the context as object and note. A missing pk becomes a 404 automatically.

Python ListView with pagination and DetailView

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

There are eight notes and three per page, so the first page shows three, the third shows two, and ?page=9 is a 404. The ?pinned=1 filter works because get_queryset() is overridden: it calls super() to get the default queryset (all notes) and narrows it.

get_queryset() is the method you override most often. Use it to filter by the current user, hide drafts or add select_related(). Because it runs per request, it can read self.request and self.kwargs; a class attribute like queryset = Note.objects.filter(...) cannot.

Add extra template variables with get_context_data(), and always start with context = super().get_context_data(**kwargs):

Python
class NoteList(ListView):
    model = Note

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["pinned_count"] = Note.objects.filter(pinned=True).count()
        return context

In a template, pagination links need only page_obj:

DJANGO
{% if page_obj.has_previous %}<a href="?page={{ page_obj.previous_page_number }}">Previous</a>{% endif %}
Page {{ page_obj.number }} of {{ paginator.num_pages }}
{% if page_obj.has_next %}<a href="?page={{ page_obj.next_page_number }}">Next</a>{% endif %}

CreateView, UpdateView and DeleteView

The editing views combine a form with a redirect. CreateView and UpdateView build a ModelForm from the fields list you provide (or from form_class if you have a custom form). On a GET request they render the empty or filled form. On a POST request they validate: a valid form is saved and the browser is redirected, an invalid form is shown again with its errors.

Where does the redirect go? To success_url if you set it, otherwise to the saved object's get_absolute_url(). Use reverse_lazy() for success_url as a class attribute, because class bodies run at import time, before the URLconf can be loaded. Inside a method, plain reverse() is fine.

DeleteView shows a confirmation page on GET and deletes on POST, then redirects to its (required) success_url.

Python Create, edit and delete notes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The sequence shows the full life cycle. An invalid POST returns status 200, not a redirect, because the form is shown again. A valid create redirects to get_absolute_url() since NoteCreate has no success_url. The lambda registered as note-list is only a stand-in so that reverse_lazy("note-list") has a name to resolve.

A few things to know before using these views in a real project:

  • fields = "__all__" is convenient, but it exposes every model field, including ones users should not set. List fields explicitly.
  • Setting values the user must not choose, such as the owner of a note, is done in form_valid(self, form): set form.instance.owner = self.request.user and then return super().form_valid(form).
  • Editing and deleting views should restrict get_queryset() so people can touch only their own objects. Permissions covers the mixins for that.
  • In real pages the form needs a CSRF token and rendered fields; Handling Forms in Views shows the template side. The test Client skips CSRF checks by default.

When to leave the generic views

Generic views shine for standard pages. Reach for a plain View or a function when a page combines several models, when a form saves to more than one table, or when the flow does not look like list-detail-edit. You can mix: subclass a generic view and override only get() or post(), or use the mixins (SingleObjectMixin, FormMixin) to assemble your own.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You want a ListView that only shows the current user's notes. What do you override?

    get_queryset() decides which rows the view works with and has access to self.request, so it is the right place to filter by user.
  2. 2. A CreateView has no success_url. Where does it redirect after a valid POST?

    Without success_url, CreateView and UpdateView use get_absolute_url() of the saved object. If the model lacks that method, Django raises ImproperlyConfigured.
  3. 3. Why is reverse_lazy() used for a class-level success_url?

    Class attributes are evaluated at import time. reverse_lazy() postpones the lookup until the value is actually used.
  4. 4. With paginate_by = 3 and 8 objects, what does ?page=9 return?

    An out-of-range page number raises Http404 in ListView. A non-numeric value is also rejected.
  5. 5. In which method do you set form.instance.owner = request.user?

    form_valid() runs after validation and before the object is saved, so you can fill fields that the user should not control.

Summary

  • ListView, DetailView, CreateView, UpdateView and DeleteView implement the five standard pages from a model.
  • Template names default to <app>/<model>_list.html, _detail.html, _form.html and _confirm_delete.html.
  • Override get_queryset() to filter, get_context_data() to add variables, and form_valid() to set server-side fields.
  • paginate_by adds page_obj, paginator and ?page= handling; out-of-range pages are 404.
  • Editing views redirect to success_url or the object's get_absolute_url(); use reverse_lazy() in class attributes.
  • List form fields explicitly and restrict querysets by owner before putting these views on the internet.

Next, learn what happens when something goes wrong in Error Pages and Exceptions.