Django Form component
Django Form components are used to initialize pages, generate HTML tags, and also validate data submitted by users (displaying error messages).
Error message display order:
- First display the error messages from field attributes, then display the error messages from local hooks.
- If the error messages from field attributes are displayed, the error messages from local hooks will not be displayed.
- If there are global hooks, the global hooks will start validation only after all data has been validated, and the error messages from global hooks will definitely be displayed.
To use Form components, you need to import forms first:
from django import forms

Next, we create a My_forms.py file in the app01 directory:
app01/My_forms.py
from django import forms
from django.core.exceptions import ValidationError
from app01 import models
class EmpForm(forms.Form):
name = forms.CharField(min_length=4, label="Name", error_messages={"min_length": "You are too short.", "required": "This field cannot be empty!"})
age = forms.IntegerField(label="Age")
salary = forms.DecimalField(label="Salary")
from django.core.exceptions import ValidationError
from app01 import models
class EmpForm(forms.Form):
name = forms.CharField(min_length=4, label="Name", error_messages={"min_length": "You are too short.", "required": "This field cannot be empty!"})
age = forms.IntegerField(label="Age")
salary = forms.DecimalField(label="Salary")
Field attributes:
- label: The text information in front of the input box.
- error_message: Customize the displayed error messages. The attribute value is a dictionary, where `required` is the key for setting the error message displayed when the field cannot be empty.
app01/views.py
from django.shortcuts import render, HttpResponse
from app01.My_Forms import EmpForm
from app01 import models
from django.core.exceptions import ValidationError
# Create your views here.
def add_emp(request):
if request.method == "GET":
form = EmpForm()
return render(request, "add_emp.html", {"form": form})
else:
form = EmpForm(request.POST)
if form.is_valid(): # Perform data validation
# Validation Successful
data = form.cleaned_data # Values that pass validation are placed in cleaned_data.
data.pop('r_salary')
print(data)
models.Emp.objects.create(**data)
return HttpResponse(
'ok'
)
# return render(request, "add_emp.html", {"form": form})
else:
print(form.errors) # Print error messages
clean_errors = form.errors.get("__all__")
print(222, clean_errors)
return render(request, "add_emp.html", {"form": form, "clean_errors": clean_errors})
from app01.My_Forms import EmpForm
from app01 import models
from django.core.exceptions import ValidationError
# Create your views here.
def add_emp(request):
if request.method == "GET":
form = EmpForm()
return render(request, "add_emp.html", {"form": form})
else:
form = EmpForm(request.POST)
if form.is_valid(): # Perform data validation
# Validation Successful
data = form.cleaned_data # Values that pass validation are placed in cleaned_data.
data.pop('r_salary')
print(data)
models.Emp.objects.create(**data)
return HttpResponse(
'ok'
)
# return render(request, "add_emp.html", {"form": form})
else:
print(form.errors) # Print error messages
clean_errors = form.errors.get("__all__")
print(222, clean_errors)
return render(request, "add_emp.html", {"form": form, "clean_errors": clean_errors})
Add the following rules to the app01/urls.py file:
path('add_emp/', views.add_emp)
HTML template:
app01/add_emp.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h3>Add Employee</h3>{#1. Write HTML Pages Manually#}<form action="" method="post">
<p>Name:<input type="text" name="name"></p>
<p>Age:<input type="text" name="age"></p>
<p>Salary:<input type="text" name="salary"></p>
<input type="submit">
</form>{#2. Implemented via the as_p method of the form object#}
{#<form action="" method="post" novalidate>#}
{# {% csrf_token %}#}
{# {{ form.as_p }}#}
{# <input type="submit">#}
{#</form>#}
{#3. Manually get the fields of the form object#}
{#<form action="" method="post" novalidate>#}
{# {% csrf_token %}#}
{# <div>#}
{# <label for="id_{{ form.name.name }}">Name</label>#}
{# {{ form.name }} <span>{{ form.name.errors.0 }}</span>#}
{# </div>#}
{# <div>#}
{# <label for="id_{{ form.age.name }}">Age</label>#}
{# {{ form.age }} <span>{{ form.age.errors.0 }}</span>#}
{# </div>#}
{# <div>#}
{# <label for="id_salary">Salary</label>#}
{# {{ form.salary }} <span>{{ form.salary.errors.0 }}</span>#}
{# </div>#}
{# <input type="submit">#}
{#</form>#}
{#4. Use a for loop to display all fields#}
{#<form action="" method="post" novalidate>#}
{# {% csrf_token %}#}
{# {% for field in form %}#}
{# <div>#}
{# <label for="id_{{ field.name }}">{{ field.label }}</label>#}
{# {{ field }} <span>{{ field.errors.0 }}</span>#}
{# </div>#}
{# {% endfor %}#}
{# <input type="submit">#}
{#</form>#}
</body>
</html>
The running result is as shown in the figure below:

Local hooks and global hooks
Define the Form class:
app01/My_forms.py
from django import forms
from django.core.exceptions import ValidationError
from app01 import models
class EmpForm(forms.Form):
name = forms.CharField(min_length=5, label="Name", error_messages={"required": "This field cannot be empty!",
"min_length": "Username is too short."})
age = forms.IntegerField(label="Age")
salary = forms.DecimalField(max_digits=5, decimal_places=2, label="Salary")
r_salary = forms.DecimalField(max_digits=5, decimal_places=2, label="Please enter the salary again.")
def clean_name(self): # Local Hook
val = self.cleaned_data.get("name")
if val.isdigit():
raise ValidationError("Username cannot be pure numbers")
elif models.Emp.objects.filter(name=val):
raise ValidationError("Username already exists!")
else:
return val
def clean(self): # Global hook to confirm whether the two entered wages are consistent.
val = self.cleaned_data.get("salary")
r_val = self.cleaned_data.get("r_salary")
if val == r_val:
return self.cleaned_data
else:
raise ValidationError("Please confirm whether the salary is consistent.")
from django.core.exceptions import ValidationError
from app01 import models
class EmpForm(forms.Form):
name = forms.CharField(min_length=5, label="Name", error_messages={"required": "This field cannot be empty!",
"min_length": "Username is too short."})
age = forms.IntegerField(label="Age")
salary = forms.DecimalField(max_digits=5, decimal_places=2, label="Salary")
r_salary = forms.DecimalField(max_digits=5, decimal_places=2, label="Please enter the salary again.")
def clean_name(self): # Local Hook
val = self.cleaned_data.get("name")
if val.isdigit():
raise ValidationError("Username cannot be pure numbers")
elif models.Emp.objects.filter(name=val):
raise ValidationError("Username already exists!")
else:
return val
def clean(self): # Global hook to confirm whether the two entered wages are consistent.
val = self.cleaned_data.get("salary")
r_val = self.cleaned_data.get("r_salary")
if val == r_val:
return self.cleaned_data
else:
raise ValidationError("Please confirm whether the salary is consistent.")
views.py file code:
app01/views.py
def add_emp(request):
if request.method == "GET":
form = EmpForm() # Initialize form object
return render(request, "add_emp.html", {"form":form})
else:
form = EmpForm(request.POST) # Pass data to the form object
if form.is_valid(): # Perform Validation
data = form.cleaned_data
data.pop("r_salary")
models.Emp.objects.create(**data)
return redirect("/index/")
else: # Validation Failed
clear_errors = form.errors.get("__all__") # Get global hook error information
return render(request, "add_emp.html", {"form": form, "clear_errors": clear_errors})
if request.method == "GET":
form = EmpForm() # Initialize form object
return render(request, "add_emp.html", {"form":form})
else:
form = EmpForm(request.POST) # Pass data to the form object
if form.is_valid(): # Perform Validation
data = form.cleaned_data
data.pop("r_salary")
models.Emp.objects.create(**data)
return redirect("/index/")
else: # Validation Failed
clear_errors = form.errors.get("__all__") # Get global hook error information
return render(request, "add_emp.html", {"form": form, "clear_errors": clear_errors})
The template file code is as follows:
app01/add_emp.html
<form action="" method="post" novalidate>
{% csrf_token %}
<div>
<label for="id_{{ form.name.name }}">Name</label>
{{ form.name }} <span>{{ form.name.errors.0 }}</span>
</div>
<div>
<label for="id_{{ form.age.name }}">Age</label>
{{ form.age }} <span>{{ form.age.errors.0 }}</span>
</div>
<div>
<label for="id_salary">Salary</label>
{{ form.salary }} <span>{{ form.salary.errors.0 }}{{ clear_errors.0 }}</span>
</div>
<div>
<label for="id_r_salary">Please enter the salary again.</label>
{{ form.r_salary }} <span>{{ form.r_salary.errors.0 }}{{ clear_errors.0 }}</span>
</div>
<input type="submit">
</form>
The running result is as shown in the figure below:

