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 访问表单

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

输入后提交数据:

相关推荐
冷雨夜中漫步5 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴5 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再6 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
喵手7 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934737 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy7 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
肖永威9 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos
TechWJ9 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
枷锁—sha9 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
abluckyboy9 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法