Django

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

You may also like...

Leave a Reply

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