๐ 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
