A Model Form automatically creates an HTML form based on a Django Model.
It reduces the amount of code required for creating forms and handling user input.
Model
↓
Model Form
↓
HTML Form
↓
Database
We will create a Model Form for the Category Model.
demo/forms.py
from django import forms
from .models import Category
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ['Name']
| Code | Purpose |
|---|---|
| forms.ModelForm | Create Form From Model |
| model | Specify Model Name |
| fields | Select Fields To Display |
The Id field is automatically generated by the database. Therefore, only the Name field is included in the form.
fields = '__all__'
However, in most projects we include only the fields required for user input.
demo/views.py
from django.shortcuts import render
from .forms import CategoryForm
def createCategory(request):
message = ""
if request.method == "POST":
form = CategoryForm(request.POST)
if form.is_valid():
form.save()
message = "Category Added Successfully."
form = CategoryForm()
else:
form = CategoryForm()
return render(request,
"createcategory.html",
{
"form": form,
"message": message
})
GET
↓
Display Form
POST
↓
Save Form Data
When the page opens, Django receives a GET request. When the user clicks the Submit button, Django receives a POST request.
form = CategoryForm(request.POST)
request.POST contains the values entered by the user in the HTML form.
These values are passed to the Model Form for validation and saving.
Create a new template to display the Category Form.
demo/templates/createcategory.html
{% extends 'base.html' %}
{% block content %}
<div class="container mt-4">
<h2>Create Category</h2>
{% if message % }
<div class="alert alert-success">
{{ message }}
</div>
{% endif %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit"
class="btn btn-primary">
Save
</button>
</form>
</div>
{% endblock %}
Django protects forms from Cross-Site Request Forgery (CSRF) attacks.
{% csrf_token %}
Every HTML form that submits data using the POST method should include the CSRF token.
{{ form.as_p }}
Django automatically generates HTML form controls using the Model Form.
<p>
<label>Name</label>
<input type="text">
</p>
The as_p method wraps each field inside a paragraph (<p>) tag.
Instead of staying on the same page, we can redirect the user to another page after saving the record.
from django.shortcuts import render, redirect
if form.is_valid():
form.save()
return redirect('/categories/')
After saving the record, Django redirects the user to the Categories page.
CategoryForm()
request.POST
form.is_valid()
form.save()
redirect()
Model
↓
Model Form
↓
HTML Form
↓
request.POST
↓
Validation
↓
Save Record
↓
Success Message / Redirect
form.save()
Tag Added Successfully.