Master Django Forms: From Basics to Advanced Usage

This article walks you through Django's Form component, explaining how it generates HTML, validates input, retains data, and integrates with models, while providing step‑by‑step code examples for defining Form classes, handling GET/POST requests, rendering templates, and customizing fields and widgets.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Django Forms: From Basics to Advanced Usage

Preface

In the previous article we introduced the basics of Django Form components; you can refer to that article for an overview.

Django Form components provide three main functions:

Generate HTML tags.

Validate submitted data.

Preserve data entered before submission.

Understanding Form Components

Without Using Form Components

Typically, a plain HTML form is written like this:

<form method="post" action="" novalidate>
    <div>
        <label>用户名:</label>
        <input type="text" name="uname">
    </div>
    <div>
        <label>密码:</label>
        <input type="text" name="upwd">
    </div>
    <div>
        <input type="submit">
    </div>
</form>

Using Form Components

When using Form components, you typically define a Form class:

from django.forms import Form, fields

class LoginForm(Form):
    uname = fields.CharField(label="用户名")
    upwd = fields.CharField(label="密码")

Then render it in a view:

from django.shortcuts import render

def login(request):
    form = LoginForm()
    return render(request, "login_f.html", {"form": form})

In the template you can render each field manually:

<form method="post" action="" novalidate>
    <div>
        <label>{{ form.uname.label }}:</label>
        {{ form.uname }}
        {{ form.uname.errors.0 }}
    </div>
    <div>
        <label>{{ form.upwd.label }}:</label>
        {{ form.upwd }}
        {{ form.upwd.errors.0 }}
    </div>
    <div>
        <input type="submit">
    </div>
</form>

Or iterate over the form object, which is useful when the form has many fields:

<form method="post" action="" novalidate>
    {% for foo in form %}
        <div>
            <label>{{ foo.label }}:</label>
            {{ foo }}
            {{ foo.errors.0 }}
        </div>
    {% endfor %}
    <div>
        <input type="submit">
    </div>
</form>

When a field is rendered, Django automatically creates the appropriate input tag with an id based on the field name.

Using Forms

Typical workflow:

Create a Form class that mirrors the corresponding model fields.

For a GET request, instantiate the Form and render the template.

For a POST request, instantiate the Form with request.POST and request.FILES, then call form.is_valid(). If valid, form.cleaned_data contains a dictionary of field values that can be saved to the database.

In the frontend, use either the manual field rendering shown above or loop over the form object.

# GET request example
if request.method == 'GET':
    form = LoginForm()
    return render(request, "login_f.html", {"form": form})

# POST request example
elif request.method == "POST":
    form = LoginForm(request.POST, request.FILES)
    if form.is_valid():
        print(form.cleaned_data)  # {'uname': '...', 'upwd': '...'}
        return HttpResponse("ok")
    return render(request, "login_f.html", {"form": form})

Form Fields

The base class for all fields is Field. Common parameters include: required=True: whether the field can be empty (default True). widget=None: widget that renders the field (e.g., input). label=None: label text displayed next to the field. help_text="": helper text shown beside the label. error_messages=None: custom error messages. validators=[]: list of custom validator functions.

Common field types: CharField: string input; options min_length, max_length, strip. IntegerField: integer input; options min_value, max_value. DecimalField: decimal input; options max_digits, decimal_places.

Other fields include DateField, TimeField, DateTimeField, FileField, ImageField, EmailField, URLField, BooleanField, etc.

Choice Fields

For single‑choice selection use ChoiceField or ModelChoiceField. For multiple selections use MultipleChoiceField or ModelMultipleChoiceField. Example:

from django.forms import fields, widgets

# Single choice with radio buttons
user = fields.CharField(
    initial=2,
    widget=widgets.RadioSelect(choices=((1,'一班'),(2,'二班')))
)

# Multiple choice with select multiple
user = fields.MultipleChoiceField(
    choices=((1,'一班'),(2,'二班')),
    initial=[1],
    widget=widgets.SelectMultiple
)

Widgets

Widgets determine the HTML representation of a field. Common widgets include TextInput, NumberInput, EmailInput, PasswordInput, Textarea, Select, RadioSelect, CheckboxInput, FileInput, etc.

Conclusion

This tutorial introduced the Django Form component from a beginner’s perspective, showing the differences between manual HTML forms and Form‑generated forms, and demonstrated how to define Form classes, handle GET and POST requests, validate data, and render forms using both explicit field rendering and iteration. It also listed common field types, choice fields, and widget options.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonDjangoWeb Developmentform-validationForms
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.