Session Overview

  • Model Forms Introduction
  • Creating First Form
  • Saving Data to Database
  • Redirecting After Save
  • Category Create Page

Model Forms Introduction

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.

Without Model Form
  • Create HTML Form
  • Read Form Values
  • Validate Data
  • Save Data
With Model Form
  • Create Form Class
  • Django Generates Form
  • Automatic Validation
  • Easy Database Save
Advantage A Model Form connects directly with a Model, making Create and Update operations much easier.
Relationship
Model
   ↓
Model Form
   ↓
HTML Form
   ↓
Database

Creating First Form

We will create a Model Form for the Category Model.

File Location
demo/forms.py
Create Category Form
from django import forms

from .models import Category

class CategoryForm(forms.ModelForm):

    class Meta:

        model = Category

        fields = ['Name']
Understanding the Code
Code Purpose
forms.ModelForm Create Form From Model
model Specify Model Name
fields Select Fields To Display
Why is Id not included?

The Id field is automatically generated by the database. Therefore, only the Name field is included in the form.

Note: If we want to display all Model fields, we can use:
fields = '__all__'
However, in most projects we include only the fields required for user input.
File Location
demo/views.py
Update View
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
                  })
Why do we check request.method?
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.

Understanding request.POST
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.

Creating the HTML Form

Create a new template to display the Category Form.

File Location
demo/templates/createcategory.html
Create Form
{% 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 %}
Result: Django automatically generates the Category form based on the Model Form.
What is csrf_token?

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.

Understanding form.as_p
{{ form.as_p }}

Django automatically generates HTML form controls using the Model Form.

Generated HTML
<p>

    <label>Name</label>

    <input type="text">

</p>

The as_p method wraps each field inside a paragraph (<p>) tag.

Redirecting After Save

Instead of staying on the same page, we can redirect the user to another page after saving the record.

Import redirect
from django.shortcuts import render, redirect
Update View
if form.is_valid():

    form.save()

    return redirect('/categories/')
Result

After saving the record, Django redirects the user to the Categories page.

Why Redirect? Redirecting prevents duplicate form submissions if the user refreshes the page after saving.

Quick Revision

Model Form
  • forms.ModelForm
  • Linked to Model
  • Automatic Form
Form Fields
  • fields
  • __all__
  • Selected Fields
POST Request
  • request.method
  • request.POST
  • Form Submission
Validation
  • is_valid()
  • Validate Input
  • Prevent Invalid Data
Save Data
  • form.save()
  • Insert Record
  • Database Table
User Experience
  • Success Message
  • Clear Form
  • Redirect
Important Methods
CategoryForm()

request.POST

form.is_valid()

form.save()

redirect()
Complete Flow
Model
   ↓
Model Form
   ↓
HTML Form
   ↓
request.POST
   ↓
Validation
   ↓
Save Record
   ↓
Success Message / Redirect

Assignment

Complete the following tasks:
  1. Create a TagForm for the Tag Model.
  2. Display only the Name field using a Model Form.
  3. Create a View to display the Tag Form.
  4. Save the submitted data using:
    form.save()
  5. Display the message:
    Tag Added Successfully.
  6. Clear the form after successfully saving the record.
  7. Add a Submit button using Bootstrap.
Company Logo
Full Stack Development Training - Python Django