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 safely
  • instance=student loads existing data into form
  • form.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

  1. User clicks “Edit”
  2. ID is passed to view
  3. Record is fetched
  4. Form is pre-filled
  5. User updates values
  6. 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

  1. Update only name and age
  2. Add cancel button
  3. Redirect after update
  4. Show old vs new values
  5. 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

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

1 thought on “Implement Update Functionality using ModelForm

Leave a Reply

Your email address will not be published. Required fields are marked *