Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add an UpdateView in Django?
Django's UpdateView is a built-in class-based view that simplifies updating model data from the frontend. It acts like an admin interface for editing existing records. In this tutorial, we'll create a complete example demonstrating how to implement UpdateView for a Student model.
Project Setup
First, create a Django project and app. Add the app to your settings and configure URLs ?
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'modelFormsDemo',
]
Project urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('modelFormsDemo.urls'))
]
App urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('student/edit/<int:pk>/', views.StudentUpdateView.as_view(), name="update"),
path('success/', views.success, name='success')
]
Creating the Model
Define a simple Student model in models.py ?
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
standard = models.CharField(max_length=100)
section = models.CharField(max_length=100)
def __str__(self):
return self.name
Creating Forms
Create forms.py in your app directory ?
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['name', 'standard', 'section']
Implementing Views
In views.py, create the UpdateView along with supporting views ?
from django.shortcuts import render
from django.views.generic.edit import UpdateView
from django.urls import reverse_lazy
from .models import Student
from .forms import StudentForm
def home(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
stu_form = StudentForm()
students = Student.objects.all()
return render(request, 'home.html', {
"stu_form": stu_form,
"students": students
})
class StudentUpdateView(UpdateView):
model = Student
fields = "__all__"
template_name = 'update_view.html'
success_url = reverse_lazy('success')
def success(request):
return render(request, 'success.html')
Creating Templates
Create a templates folder with three HTML files ?
home.html
<!DOCTYPE html>
<html>
<head>
<title>Student Management</title>
</head>
<body>
<h2>Add New Student</h2>
<form method="post">
{% csrf_token %}
{% for field in stu_form %}
{{ field.errors }}<br>
{{ field.label_tag }}: {{ field }}<br><br>
{% endfor %}
<button type="submit">Add Student</button>
</form>
<h2>Existing Students</h2>
{% for student in students %}
<p>{{ student.name }} - <a href="{% url 'update' student.pk %}">Edit</a></p>
{% endfor %}
</body>
</html>
update_view.html
<!DOCTYPE html>
<html>
<head>
<title>Update Student</title>
</head>
<body>
<h2>Update Student Information</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Update</button>
<a href="{% url 'home' %}">Cancel</a>
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h2>Student Updated Successfully!</h2>
<a href="{% url 'home' %}">Back to Home</a>
</body>
</html>
How UpdateView Works
The StudentUpdateView class inherits from Django's UpdateView and requires these key attributes:
- model: Specifies which model to update
- fields: Defines which fields can be edited
- template_name: Template for rendering the update form
- success_url: Redirect URL after successful update
Running the Application
After setting up the files, run migrations and start the development server ?
python manage.py makemigrations python manage.py migrate python manage.py runserver
Visit http://127.0.0.1:8000/ to add students, then click "Edit" links to update existing records using the UpdateView.
Conclusion
Django's UpdateView provides a clean, reusable way to handle model updates with minimal code. It automatically handles form rendering, validation, and database updates while maintaining separation of concerns.
