Master Django Form Validation: Build a Robust Registration Page
This tutorial walks you through creating a Django registration page using the built‑in Form component, demonstrating how to validate user input, display error messages, preserve submitted data, and compare a plain view implementation with a Form‑based approach.
Introduction
Hey, everyone, I’m a coder sharing a new skill: the Django Form component.
What Is the Form Component?
The Form component is primarily used to validate form data in projects where the front‑end and back‑end are not separated.
Why Use a Form Component?
In non‑separated projects, Form helps check fields such as nickname existence, password length, and phone‑number format, and it displays error messages directly on the page.
Below is a simple registration example.
Plain Version Registration
Code
from django.urls import path
from web import views
urlpatterns = [
path('reg/', views.reg,),
] def reg(request):
if request.method == "GET":
return render(request, "reg.html")
nick = request.POST.get("nick")
pwd = request.POST.get("pwd")
phone = request.POST.get("phone")
error = {}
if len(pwd) < 6:
error["pwd"] = "密码小于6位"
if len(phone) != 11:
error["phone"] = "手机号格式错误"
if not error:
print("写入数据库", nick, pwd, phone)
return HttpResponse("注册成功")
else:
return render(request, "reg.html", {"error": error}) <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<div style="width:40%;margin:auto">
<form action="" method="post">
<div><input name="nick" type="text" placeholder="昵称"></div>
<div>
<input name="pwd" type="password" placeholder="密码">
<span>{{ error.pwd }}</span>
</div>
<div>
<input name="phone" type="text" placeholder="手机号">
<span>{{ error.phone }}</span>
</div>
<div><input type="submit"></div>
</form>
</div>
</body>
</html>Result When Input Is Correct
Result When Input Is Incorrect
Although errors are shown, the submitted data disappears after the page refresh because a normal HTML form performs a full page reload.
Form‑Based Registration
Before using the Form component, set LANGUAGE_CODE = 'zh-hans' in settings.py.
Code
from django.shortcuts import render, HttpResponse
from django.forms import Form, fields, widgets
class RegForm(Form):
name = fields.CharField(widget=widgets.TextInput(attrs={"placeholder": "昵称"}))
pwd = fields.CharField(min_length=6, widget=widgets.TextInput(attrs={"placeholder": "密码"}))
phone = fields.CharField(min_length=11, max_length=11, widget=widgets.TextInput(attrs={"placeholder": "手机号"}))
def reg(request):
if request.method == "GET":
form = RegForm()
return render(request, "reg.html", {"form": form})
form = RegForm(request.POST, request.FILES)
if form.is_valid():
result = form.clean()
print(result)
return HttpResponse("登录")
return render(request, "reg.html", {"form": form}) <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<div style="width:40%;margin:auto">
<form action="" method="post" novalidate>
{% for foo in form %}
<div>
{{ foo }}
<span style="color:red">{{ foo.errors.0 }}</span>
</div>
{% endfor %}
<div><input type="submit"></div>
</form>
</div>
</body>
</html>Result When Input Is Correct
Result When Input Is Incorrect
Even though the page refreshes, the Form component retains the previously entered data and shows validation error messages.
Form Summary
From the examples you can see that Django’s Form component provides at least three essential features:
Generation of HTML form fields.
Validation of submitted data.
Preservation of user‑entered data after a failed submission.
If you are developing with Django and your project does not separate front‑end and back‑end, using the Form component is highly recommended.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
