Implement Update Functionality using ModelForm
π Introduction
After adding records to the database, we often need to edit or update existing records.
In Django, updating records using ModelForm is very simple:
- fetch the record
- load it into form
- update values
- save changes
π― Program Statement
π Implement update functionality using ModelForm.
π§ Concept
This program uses:
ModelForm- fetching record using
id - passing instance to form
- saving updated data
βοΈ Step 1: Model (Same as before)
π File: models.py
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
course = models.CharField(max_length=100)
email = models.EmailField(unique=True)
βοΈ Step 2: ModelForm (Same as Post 48)
π File: forms.py
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
βοΈ Step 3: Create Update View
π File: views.py
πΉ Path:
myproject/myapp/views.py
πΉ Code:
from django.shortcuts import render, get_object_or_404
from .models import Student
from .forms import StudentForm
def update_student(request, id):
student = get_object_or_404(Student, id=id)
if request.method == 'POST':
form = StudentForm(request.POST, instance=student)
if form.is_valid():
form.save()
return render(request, 'update_student.html', {
'form': form,
'success': True
})
else:
form = StudentForm(instance=student)
return render(request, 'update_student.html', {
'form': form
})
π§ Explanation
get_object_or_404()fetches record safelyinstance=studentloads existing data into formform.save()updates record
βοΈ Step 4: URL Mapping
π File: urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('update/<int:id>/', views.update_student, name='update_student'),
]
βοΈ Step 5: Create Template
π File: update_student.html
πΉ Path:
myproject/templates/update_student.html
πΉ Code:
<!DOCTYPE html>
<html>
<head>
<title>Update Student</title>
</head>
<body>
<h1>Update Student Record</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Update</button>
</form>
<hr>
{% if success %}
<h2 style="color: green;">Record Updated Successfully!</h2>
{% endif %}
</body>
</html>
βοΈ Step 6: Add Update Link in Table (Important)
π Modify Post 46 table
π File: student_table.html
Add:
<td>
<a href="/update/{{ s.id }}/">Edit</a>
</td>
πΉ Example Row:
<tr>
<td>{{ s.id }}</td>
<td>{{ s.name }}</td>
<td>{{ s.age }}</td>
<td>{{ s.course }}</td>
<td>{{ s.email }}</td>
<td><a href="/update/{{ s.id }}/">Edit</a></td>
</tr>
βοΈ Step 7: Run Server
python manage.py runserver
π Step 8: Output
π Open:
http://127.0.0.1:8000/update/1/
β Example:
Before update:
Name: Cherry Age: 15
After update:
Name: Cherry Age: 16
π§ How It Works
- User clicks “Edit”
- ID is passed to view
- Record is fetched
- Form is pre-filled
- User updates values
form.save()updates database
π₯ Key Concepts
Fetch Record Safely
get_object_or_404(Student, id=id)
Load Existing Data
StudentForm(instance=student)
Update Data
StudentForm(request.POST, instance=student)
Save Changes
form.save()
β οΈ Common Errors
β Forgot instance=student
π Form will create new record instead of updating
β Using .get() instead of safe method
Better:
get_object_or_404()
β URL mismatch
Ensure:
update/<int:id>/
β Form not pre-filled
Check:
StudentForm(instance=student)
β Duplicate email error
If email is changed to existing value
π§ͺ Practice Questions
- Update only name and age
- Add cancel button
- Redirect after update
- Show old vs new values
- Add success message popup
π€ Viva Questions & Answers
1. What is update operation in Django?
Update operation modifies existing records in the database.
2. What is the use of instance in ModelForm?
It binds the form to an existing object for updating.
3. What happens if instance is not used?
A new record will be created instead of updating.
4. What is get_object_or_404()?
It fetches the object or returns a 404 error if not found.
5. Why do we pass id in URL?
To identify which record should be updated.
6. How is form pre-filled?
Using instance=student.
7. What does form.save() do here?
It updates the existing record in database.
8. Can we update only selected fields?
Yes, by modifying fields in ModelForm.
9. What is difference between add and update form?
Add form has no instance; update form uses instance.
π Next Post: Implement Delete Functionality with Confirmation Page
π Back to List: Django Programs (60 Questions with Solutions)
Further Reading
Introduction to Django Framework and its Features
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET

[…] Update dataπ π Solution: /django-update […]