CreateView & UpdateView

Generic editing views build, validate and save forms for you.

Syntaxclass PostCreateView(CreateView): model = Post

CreateView and UpdateView generate a ModelForm, render it, validate the submission and save it — the whole form pattern in a few lines. DeleteView handles deletions with a confirmation page.

Set fields (or a custom form_class) and a success_url to redirect to after saving.

Example

Example · python
from django.views.generic import CreateView, UpdateView
from django.urls import reverse_lazy
from .models import Post

class PostCreateView(CreateView):
    model = Post
    fields = ["title", "body", "published"]
    success_url = reverse_lazy("index")

class PostUpdateView(UpdateView):
    model = Post
    fields = ["title", "body", "published"]

When to use it

  • A developer uses CreateView to build a post creation form with automatic validation and redirect on success.
  • A team uses UpdateView to handle editing an existing record, pre-populating the form from the database.
  • A developer uses DeleteView to add a confirmation page before permanently removing a record.

More examples

CreateView for new post

Creates a form from the Post model fields and redirects to the list view on successful save.

Example · python
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Post

class PostCreateView(CreateView):
    model = Post
    fields = ["title", "body"]
    template_name = "blog/post_form.html"
    success_url = reverse_lazy("post-list")

UpdateView to edit a record

Pre-populates a form with existing Post data and redirects to the post's page after saving.

Example · python
from django.views.generic.edit import UpdateView

class PostUpdateView(UpdateView):
    model = Post
    fields = ["title", "body"]
    template_name = "blog/post_form.html"

    def get_success_url(self):
        return self.object.get_absolute_url()

DeleteView with confirmation

Renders a confirmation page and deletes the Post on POST submission, then redirects to the list.

Example · python
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy

class PostDeleteView(DeleteView):
    model = Post
    template_name = "blog/post_confirm_delete.html"
    success_url = reverse_lazy("post-list")

# Template: <form method="post">{% csrf_token %}<button>Confirm Delete</button></form>

Discussion

  • Be the first to comment on this lesson.