An UpdateView is a built-in class-based view used to edit an existing record in the database. It automatically handles fetching the record, showing a pre-filled form, validating input, and saving changes.
- Specify the model that contains the record to be updated.
- Define the form fields that should appear in the update form.
- Provide the template used to render the form.
- Set a success URL to redirect after the update is saved.
Example: Consider a project named 'geeksforgeeks' having an app named 'geeks'. After you have a project and an app, let's create a model of which we will be creating instances through our view.
In geeks/models.py:
from django.db import models
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
# fields of the model
title = models.CharField(max_length = 200)
description = models.TextField()
# renames the instances of the model with their title name
def __str__(self):
return self.title
After creating this model, we need to run two commands in order to create Database for the same.
Python manage.py makemigrations
Python manage.py migrate
Now, create instances of this model using the Django shell by running the following command in the terminal:
Python manage.py shell
Next enter following commands:
>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create( title="title1", description="description1")
>>> GeeksModel.objects.create(title="title2", description="description2")
>>> GeeksModel.objects.create(title="title3", description="description3")
Now that the backend setup complete, verify that instances have been created by visiting:

To create an UpdateView, it is only necessary to specify the model. Django’s UpdateView will then look for a template named app_name/modelname_form.html. Here, expected template path is geeks/templates/geeks/geeksmodel_form.html.
Next, create the class-based view in geeks/views.py:
from django.views.generic.edit import UpdateView
# Relative import of GeeksModel
from .models import GeeksModel
class GeeksUpdateView(UpdateView):
# specify the model you want to use
model = GeeksModel
# specify the fields
fields = [
"title",
"description"
]
success_url ="/"
Now, create a url path to map the view in geeks/urls.py:
from django.urls import path
# importing views from views.py
from .views import GeeksUpdateView
urlpatterns = [
# <pk> is identification for id field, <slug> can also be used
path('<pk>/update', GeeksUpdateView.as_view()),
]
Next, create a template in templates/geeks/geeksmodel_form.html:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
Now, visit the corresponding page to verify that the UpdateView is working as expected.
