Django

Create a ModelForm to Add Records to the Database

๐Ÿ“Œ Introduction

In earlier posts, we inserted records using:

  • Django shell
  • Admin panel

But in real applications, users enter data through forms on web pages.

๐Ÿ‘‰ Instead of manually creating forms, Django provides ModelForm, which:

  • automatically creates form fields from model
  • reduces code
  • handles validation

๐ŸŽฏ Program Statement

๐Ÿ‘‰ Create a ModelForm to add records to the database.


๐Ÿง  Concept

This program uses:

  • models.py โ†’ database structure
  • forms.py โ†’ ModelForm
  • views.py โ†’ handle form submission
  • template โ†’ display form

โš™๏ธ Step 1: Model (Already Created)


๐Ÿ“ File: models.py

๐Ÿ”น Path:

myproject/myapp/models.py

๐Ÿ”น Code:

from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
course = models.CharField(max_length=100)
email = models.EmailField(unique=True)

def __str__(self):
return self.name

โš™๏ธ Step 2: Create ModelForm


๐Ÿ“ File: forms.py

๐Ÿ”น Path:

myproject/myapp/forms.py

๐Ÿ”น Code:

from django import forms
from .models import Student

class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'

๐Ÿง  Explanation

  • ModelForm automatically creates fields from model
  • fields = '__all__' โ†’ includes all model fields

โš™๏ธ Step 3: Create View


๐Ÿ“ File: views.py

๐Ÿ”น Path:

myproject/myapp/views.py

๐Ÿ”น Code:

from django.shortcuts import render
from .forms import StudentForm

def add_student(request):
success = False

if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
success = True
else:
form = StudentForm()

return render(request, 'add_student.html', {
'form': form,
'success': success
})

๐Ÿง  Explanation

  • Form is created using StudentForm()
  • On submission โ†’ validated
  • form.save() inserts record into database

โš™๏ธ Step 4: URL Mapping


๐Ÿ“ File: urls.py

๐Ÿ”น Path:

myproject/myproject/urls.py

๐Ÿ”น Code:

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('add-student/', views.add_student, name='add_student'),
]

โš™๏ธ Step 5: Create Template


๐Ÿ“ File: add_student.html

๐Ÿ”น Path:

myproject/templates/add_student.html

๐Ÿ”น Code:

<!DOCTYPE html>
<html>
<head>
<title>Add Student</title>
</head>
<body>

<h1>Add Student Record</h1>

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Student</button>
</form>

<hr>

{% if success %}
<h2 style="color: green;">Record Added Successfully!</h2>
{% endif %}

</body>
</html>

๐Ÿง  Explanation

  • {{ form.as_p }} displays form fields
  • form.save() stores data
  • Success message confirms insertion

โš™๏ธ Step 6: Run Server

python manage.py runserver

๐ŸŒ Step 7: Output

๐Ÿ‘‰ Open:

http://127.0.0.1:8000/add-student/

โœ… Example Input:


โœ… Output:

Record Added Successfully!

๐Ÿง  How It Works

  1. Model defines structure
  2. ModelForm creates form automatically
  3. User fills form
  4. View validates data
  5. form.save() inserts record
  6. Template shows success message

๐Ÿ”ฅ Key Concepts


ModelForm

class StudentForm(forms.ModelForm):

Meta Class

class Meta:
model = Student

Include Fields

fields = '__all__'

Save Record

form.save()

Display Form

{{ form.as_p }}

โš ๏ธ Common Errors


โŒ Forgot to import model in forms

from .models import Student

โŒ Forgot CSRF token

{% csrf_token %}

โŒ Duplicate email error

Because:

email = models.EmailField(unique=True)

โŒ Form not saving

Check:

if form.is_valid():
form.save()

โŒ Wrong field name

Model and form fields must match


๐Ÿงช Practice Questions

  1. Exclude email field from form
  2. Add placeholder to fields
  3. Add custom label names
  4. Redirect after submission
  5. Add reset button

๐ŸŽค Viva Questions & Answers


1. What is ModelForm in Django?

ModelForm is a form class that automatically creates form fields from a model.


2. Why do we use ModelForm?

It reduces code and automatically handles form creation and validation.


3. What is the use of Meta class?

The Meta class defines which model and fields the form will use.


4. What does fields = '__all__' mean?

It includes all fields from the model in the form.


5. What is form.save()?

It saves form data into the database.


6. Why is ModelForm better than normal forms?

Because it automatically links with database models.


7. Can we exclude fields in ModelForm?

Yes, using:

exclude = ['field_name']

8. What happens if form is invalid?

The form is not saved and errors are displayed.


9. Where is validation performed?

Validation is automatically handled by Django forms.


10. Why is this program important?

It is the foundation for CRUD operations in Django applications.


๐Ÿ‘‰ Next Post: Implement Update Functionality using ModelForm
๐Ÿ‘‰ 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 *