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

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

输入后提交数据:

相关推荐
Mallow Flowers12 分钟前
Python训练营-Day31-文件的拆分和使用
开发语言·人工智能·python·算法·机器学习
蓝婷儿37 分钟前
Python 爬虫入门 Day 2 - HTML解析入门(使用 BeautifulSoup)
爬虫·python·html
struggle20251 小时前
Burn 开源程序是下一代深度学习框架,在灵活性、效率和可移植性方面毫不妥协
人工智能·python·深度学习·rust
腾飞开源2 小时前
17_Flask部署到网络服务器
python·flask·python web开发·flask快速入门教程·flask框架·flask视频教程·flask会话技术
Mikhail_G2 小时前
Python应用八股文
大数据·运维·开发语言·python·数据分析
mikes zhang2 小时前
Flask文件上传与异常处理完全指南
后端·python·flask
烛阴2 小时前
深入浅出地理解Python元类【从入门到精通】
前端·python
weixin_464078073 小时前
Python学习小结
python·学习
ubax4 小时前
day 51 python打卡
开发语言·python
laocooon5238578864 小时前
基于Python的TCP应用案例,包含**服务器端**和**客户端**的完整代码
网络·python·tcp/ip