Django学习笔记-表单(forms)的使用

在Django中提供了了form表单,可以更为简单的创建表单模板信息,简化html的表单。

一、网页应用程序中表单的应用

表单通常用来作为提交数据时候使用。

1.1 创建表单模板文件夹

在项目文件夹下创建一个template文件夹,用于存储所有的html模板文件。

1.2 在文件夹下创建对应的html模板文件

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Name</title>
</head>
<body>
    <form>
        <label for="name">名字</label>
        <input type="text" id="name" name = "name" maxlength="10" required/>
        <label for="phone">电话</label>
        <input id="phone" type="text" name="phone" maxlength="11" required/>
    </form>
</body>
</html>

1.3 添加模板文件路径到settings.py文件中

填写项目的相对路径即可。

1.4 路由设置

在app中views.py文件中添加响应函数:

python 复制代码
def get_person(request):
    """method of re match"""

    return render(request,"person.html")

在urls.py添加路由设置

python 复制代码
urlpatterns = [
    path('test/2023', serverapp_views.test),        # 精确匹配
    path('converter/<int:num>', serverapp_views.converter),         # 格式转换
    re_path(r'^re/(?P<num>[0-9]{1,4})/$', serverapp_views.rematch),         # 正则表达式,通过添加起止符限制匹配,避免中间多级路径后匹配到,造成错误匹配。
    path('person', serverapp_views.get_person),        # 获取人员信息
]

1.5 访问表单

直接浏览器通过"http://127.0.0.1:8000/serverapp/person" 访问:

二、使用Django的forms表单替换html的表单

2.1 在App中创建一个forms.py文件统一管理表单

2.2 创建表单类PersonForm

定义的属性就对应表单中的每一项。

python 复制代码
# _*_ coding:utf-8 _*_

from django import forms


class PersonForm(forms.Form):
    """人员表单类"""

    name = forms.CharField(label="name", max_length=10)
    phone = forms.CharField(label="phone", max_length=11)

2.3 修改html模块,用form替代HTML字待的表单

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Name</title>
</head>
<body>
    <!--action 是访问的url-->
    <form action="/serverapp/views/get_personform" method="post">
        {% csrf_token %}        <!--防止跨域攻击-->
        {{ personform }}        <!--引用表单,views函数中定义的名称一致-->
        <button type="submit">提交</button>
    </form>
</body>
</html>

2.4 views.py中定义函数引用表单

通过路由处理函数可以对访问信息进行识别,获取表单的基本信并进行处理。

python 复制代码
def get_personform(request):
    """method of re match"""

    if request.method == "POST":
        # 获取表单
        form = PersonForm(request.POST)
        # 判断是否为有效表单
        if form.is_valid():
            # 使用cleaned_data获取请求数据
            name = form.cleaned_data["name"]
            phone = form.cleaned_data["phone"]

            # 返回数据
            return HttpResponse(f"Data is :\r\n name:{name}\r\nphone:{phone}")
        else:
            return HttpResponseRedirect("/error/")
    # Get方法访问
    else:
        # 重定向到登录表单页面
        return render(request, "personform.html", {'personform':PersonForm()})

2.5 添加路径到urls.py中

python 复制代码
from django.urls import path,re_path
from serverapp import views as serverapp_views


urlpatterns = [
    path('test/2023', serverapp_views.test),        # 精确匹配
    path('converter/<int:num>', serverapp_views.converter),         # 格式转换
    re_path(r'^re/(?P<num>[0-9]{1,4})/$', serverapp_views.rematch),         # 正则表达式,通过添加起止符限制匹配,避免中间多级路径后匹配到,造成错误匹配。
    path('person', serverapp_views.get_person),        # 获取人员信息
    path('personform', serverapp_views.get_personform),        # 使用表单获取人员信息
]

2.6 访问表单

放到后直接获取到表单模板。

输入后提交数据:

相关推荐
web1508541593517 分钟前
Python异步编程详解
开发语言·python
金色旭光18 分钟前
f-string 高效的字符串格式化
python
是小菜呀!36 分钟前
一文讲清python、anaconda的安装以及pycharm创建工程
开发语言·python·pycharm
m0_7136963637 分钟前
python训练 60天挑战-day31
开发语言·人工智能·python·python学习打卡
2401_861412142 小时前
Python编程从入门到实践 PDF 高清版
python·pdf
2301_778658802 小时前
【Python训练营打卡】day31 @浙大疏锦行
python
敲键盘的小夜猫3 小时前
如何理解大模型的幻觉输出及RAG技术的应用与实战案例
开发语言·python
三道杠卷胡3 小时前
【AI News | 20250520】每日AI进展
人工智能·pytorch·python·语言模型·github
STONE_KKK3 小时前
Django快速入门篇
数据库·django·sqlite
Takoony3 小时前
verify_ssl 与 Token 验证的区别详解
python