๐ 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 structureforms.pyโ ModelFormviews.pyโ handle form submissiontemplateโ 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
ModelFormautomatically creates fields from modelfields = '__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 fieldsform.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:
- Name: Rahul
- Age: 23
- Course: BCA
- Email: rahul@example.com
โ Output:
Record Added Successfully!
๐ง How It Works
- Model defines structure
- ModelForm creates form automatically
- User fills form
- View validates data
form.save()inserts record- 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
- Exclude email field from form
- Add placeholder to fields
- Add custom label names
- Redirect after submission
- 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
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
