How to add an UpdateView in Django?

Server Side ProgrammingProgrammingPython

UpdateView is a view in Django which is used to update any model data from frontend. It is a built-in view that can be easily applied. It acts like an Admin page in updating the view. In this article, we will take an example and demonstrate how to use UpdateView in Django.

First of all, create a Django project and an app. I created the project with the name "tutorial11" and the app with the name "modelFormsDemo".

Now, let's do some basic things.

Add app in

INSTALLED_APPS+ = ['modelFormsDemo']

In project's, include app's urls.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
   path('', include('modelFormsDemo.urls'))

In app's, add the following −

from django.urls import path,include
from . import views

urlpatterns = [
   path('', views.home,name="home"),
   path('student/edit//', views.StudentUpdateView.as_view(), name="update"),
   path('success/', views.success, name='success')

Here we created three urls; one for rendering the frontend, one for UpdateView for updating, and success for redirecting after updating.


In, add this −

from django.db import models

# Create your models here
class Student(models.Model):

Here we created a simple model. It is a very basic model.

In, add the following −

from django.shortcuts import render
from .forms import StudentForm
from django.views.generic.edit import UpdateView
from .models import Student
from django.urls import reverse_lazy

# Create your views here.
def home(request):
   if request.method=='POST':
      if form.is_valid():
   return render(request,'home.html', {"stu_form":stuForm})
class StudentUpdateView(UpdateView):
def success(request):
   return render(request,'success.html')

Here we haven't done anything complex; we just gave a name to the model, the fields, and the template which we are going to render. Also, we defined a function which will tell what to do after updating.

Create in app directory and add the following lines −

from django import forms
from .models import Student

class StudentForm(forms.ModelForm):
   class Meta:

Here we simply created a form which we will render.

Now create a templates folder and add three files inside it; home.html, update_view.html, and success.html.

In home.html and update_view.html

<!DOCTYPE html>
      {% for fm in stu_form %}
      <form method="post">
         <button type="submit">Submit</button>

In success.html, add the following lines −

<!DOCTYPE html>

With that, everything is set. Now you can proceed to check the output.



Now if you go on object id)/ then you will see our update_view.html.


Updated on 14-Mar-2022 06:03:52