7.14. Django Form component

发布时间 :2025-10-25 12:24:15 UTC      

The Django Form component is used to initialize the page, generate HTML tags, and validate the data submitted by the user (displaying error messages).

报错信息显示顺序:

  • Displays the error message in the field properties before displaying the error message for the local hook.

  • If the error message for the field property is displayed, the error message for the local hook is not displayed.

  • If there is a global hook, the global hook will not be verified until all the data has been verified, and the error message of the global hook must be displayed.

To use the Form component, you need to import forms first:

from django import forms

image0

Next, we create a My_forms.py under the app01 directory:

7.14.1. 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="姓名",
error_messages={"min_length": "你太短了", "required":
"该字段不能为空!"})
    age = forms.IntegerField(label="年龄")
    salary = forms.DecimalField(label="工资")

字段属性:

  • label Enter the text information in front of the box

  • error_message Customizes the error message displayed, and the attribute value is the dictionary, where required is the key that sets the error message that cannot be empty.

7.14.2. 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():  # 进行数据校验
            # 校验成功
            data = form.cleaned_data  #
校验成功的值,会放在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)    # 打印错误信息
            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:

7.14.3. app01/add_emp.html

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title></title></head><body><h3>添加员工</h3>{#1、自己手动写HTML页面#}<formaction=""method="post"><p>姓名:<inputtype="text"name="name"></p><p>年龄:<inputtype="text"name="age"></p><p>工资:<inputtype="text"name="salary"></p><inputtype="submit"></form>{#2、通过form对象的as_p方法实现#}
{#<formaction=""method="post"novalidate>#} {# {% csrf_token %}#} {# {{
form.as_p }}#} {#<inputtype="submit">#} {#</form>#}
{#3、手动获取form对象的字段#} {#<formaction=""method="post"novalidate>#}
{# {% csrf_token %}#} {#<div>#} {#<labelfor="id_{{ form.name.name
}}">姓名</label>#} {# {{ form.name }}<span>{{ form.name.errors.0
}}</span>#} {#</div>#} {#<div>#} {#<labelfor="id_{{ form.age.name
}}">年龄</label>#} {# {{ form.age }}<span>{{ form.age.errors.0
}}</span>#} {#</div>#} {#<div>#} {#<labelfor="id_salary">工资</label>#}
{# {{ form.salary }}<span>{{ form.salary.errors.0 }}</span>#} {#</div>#}
{#<inputtype="submit">#} {#</form>#} {#4、用for循环展示所有字段#}
{#<formaction=""method="post"novalidate>#} {# {% csrf_token %}#} {# {%
for field in form %}#} {#<div>#} {#<labelfor="id_{{ field.name }}">{{
field.label }}</label>#} {# {{ field }}<span>{{ field.errors.0
}}</span>#} {#</div>#} {# {% endfor %}#} {#<inputtype="submit">#}
{#</form>#}</body></html>

The running result is shown in the following figure:

image1

Local hooks and global hooks

Define the Form class:

7.14.4. 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="姓名",
error_messages={"required": "该字段不能为空!",

 "min_length": "用户名太短。"})
    age = forms.IntegerField(label="年龄")
    salary = forms.DecimalField(max_digits=5, decimal_places=2,
label="工资")
    r_salary = forms.DecimalField(max_digits=5, decimal_places=2,
label="请再输入工资")
    def clean_name(self):  # 局部钩子
        val = self.cleaned_data.get("name")
        if val.isdigit():
            raise ValidationError("用户名不能是纯数字")
        elif models.Emp.objects.filter(name=val):
            raise ValidationError("用户名已存在!")
        else:
            return val
    def clean(self):  # 全局钩子 确认两次输入的工资是否一致。
        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("请确认工资是否一致。")

Views.py file code:

7.14.5. app01/views.py

def add_emp(request):
    if request.method == "GET":
        form = EmpForm()  # 初始化form对象
        return render(request, "add_emp.html", {"form":form})
    else:
        form = EmpForm(request.POST)  # 将数据传给form对象
        if form.is_valid():  # 进行校验
            data = form.cleaned_data
            data.pop("r_salary")
            models.Emp.objects.create(\**data)
            return redirect("/index/")
        else:  # 校验失败
            clear_errors = form.errors.get("__all__")  #
获取全局钩子错误信息
            return render(request, "add_emp.html", {"form": form,
"clear_errors": clear_errors})

The template file code is as follows:

7.14.6. app01/add_emp.html

<formaction=""method="post"novalidate>{% csrf_token
%}<div><labelfor="id_{{ form.name.name }}">姓名</label>{{ form.name
}}<span>{{ form.name.errors.0 }}</span></div><div><labelfor="id_{{
form.age.name }}">年龄</label>{{ form.age }}<span>{{ form.age.errors.0
}}</span></div><div><labelfor="id_salary">工资</label>{{ form.salary
}}<span>{{ form.salary.errors.0 }}{{ clear_errors.0
}}</span></div><div><labelfor="id_r_salary">请再输入工资</label>{{
form.r_salary }}<span>{{ form.r_salary.errors.0 }}{{ clear_errors.0
}}</span></div><inputtype="submit"></form>

The running result is shown in the following figure:

image2

https://www.runoob.com/wp-content/uploads/2020/05/1563239932711.png

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.