首页 > 编程语言 >Python的Django框架中forms表单类的使用方法详解

Python的Django框架中forms表单类的使用方法详解

时间:2022-12-16 11:37:17浏览次数:59  
标签:form Python 错误信息 request Django forms models error


Form

Form的验证思路

前端:form表单

后台:创建form类,当请求到来时,先匹配,匹配出正确和错误信息。

Django的Form验证实例

创建project,进行基础配置文件配置

Python的Django框架中forms表单类的使用方法详解_html

Python的Django框架中forms表单类的使用方法详解_python_02

Python的Django框架中forms表单类的使用方法详解_python_03

settings.py

settings.py之csrf注销

__init__.py

urls.py

views.account.py:


from django.shortcuts import render,HttpResponsefrom app01.forms import Form1

def form1(request):
if request.method=="POST": #这里POST一定要大写
#通常获取请求信息
#request.POST.get("user",None)
#request.POST.get("pwd",None)
#获取请求内容,做验证
f = Form1(request.POST) #request.POST:将接收到的数据通过Form1验证
if f.is_valid(): #验证请求的内容和Form1里面的是否验证通过。通过是True,否则False。
print(f.cleaned_data) #cleaned_data类型是字典,里面是提交成功后的信息
else: #错误信息包含是否为空,或者符合正则表达式的规则
print(type(f.errors),f.errors) #errors类型是ErrorDict,里面是ul,li标签
return render(request,"account/form1.html",{"error":f.errors})
return render(request,"account/form1.html")


html:


<body>{#{{ error }}接收后台返回的错误信息封装在ul,li标签里面:#}
{{ error }}
<form action="/form1/" method="POST">
<div>
<input type="text" name="user" />
</div>
<div>
<input type="text" name="pwd" />
</div>
<div>
<input type="submit" value="提交" />
</div>
</form>
</body>


forms.py:

from django import formsclass Form1(forms.Form):
user = forms.CharField()
pwd = forms.CharField()


访问页面:

没有输入内容后提交,通过模板语言展示了错误信息

Python的Django框架中forms表单类的使用方法详解_css_04

Django强大之form验证时不用自定义错误信息就可以返回错误信息到前端以标签方式展现。

.is_valid():返回True或者False

.cleaned_data:通过验证后的数据

errors:
.error.get("user",None)error封装所有的错误信息,如果没有获取到,默认为None。

如:

Python的Django框架中forms表单类的使用方法详解_css_05

.error.get["pwd"]直接获取到ul、li。

如:

Python的Django框架中forms表单类的使用方法详解_python_06

forms.py

from django import formsclass Form1(forms.Form):
user = forms.CharField()
pwd = forms.CharField()


HTML:


<form action="/form1/" method="POST">        <div class="input-group">
{#接收后台传过来的form对象,自动生成input标签#}
{{ form.user }}
{#从后台传过来的error是字典,直接{{ error.user.0 }}呈现错误信息#}
       {#如果后台返回了错误信息,将错误信息放入span标签,在页面显示,否则不显示#}
{% if error.user.0 %}
<span>{{ error.user.0 }}</span>
{% endif %}
</div>
<div class="input-group">
{{ form.pwd }}
{% if error.pwd.0 %}
<span>{{ error.pwd.0 }}</span>
{% endif %}
</div>
<div>
<input type="submit" value="提交" />
</div>
</form>


account.py


def form1(request):    if request.method == "POST":
f = Form1(request.POST)
if f.is_valid():
print(f.cleaned_data)
else:
return render(request,"account/form1.html",{"error":f.errors,"form":f})
else:
# 如果不是post提交数据,就不传参数创建对象,并将对象返回给前台,直接生成input标签,内容为空
f = Form1()
return render(request,"account/form1.html",{"form":f})
return render(request,"account/form1.html")


注:

Python的Django框架中forms表单类的使用方法详解_html_07

 页面展示:

Python的Django框架中forms表单类的使用方法详解_html_08

注:这里的input标签是后端返回form对象到前端通过{{ form.xxx }}所创建的

更强大的功能:

 forms里面的字段:


required:是否可以为空。required=True 不可以为空,required=False 可以为空max_length=4 最多4个值,超过不会显示
min_length=2 至少两个值,少于两个会返回提示信息
error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'} 自定义错误信息,invalid 是格式错误
widget=forms.TextInput(attrs={'class': 'c1'}) 给自动生成的input标签自定义class属性
widget=forms.Textarea() 生成Textarea标签。widget默认生成input标签


实战:

models.py


from django.db import models# Create your models here.
class Author(models.Model):
"""
作者
"""
name = models.CharField(max_length=100)
age = models.IntegerField()

class BookType(models.Model):
"""
图书类型
"""
caption = models.CharField(max_length=64)

class Book(models.Model):
"""
图书
"""
name = models.CharField(max_length=64)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10,decimal_places=2)
pubdate = models.DateField()

authors = models.ManyToManyField(Author)
book_type = models.ForeignKey(BookType)


forms.py:


from django import formsfrom app01 import models

class Form1(forms.Form):
user = forms.CharField(
widget=forms.TextInput(attrs={'class': 'c1'}),
error_messages={'required': '用户名不能为空'}, )
pwd = forms.CharField(max_length=4, min_length=2,required=True)
email = forms.EmailField(error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'})

memo = forms.CharField(
widget=forms.Textarea()
)
#直接写数据
# user_type_choice = (
# (0, '普通用户'),
# (1, '高级用户'),
# )
#通过BookType表查询信息,values_list拿到的是元组。id作为value显示,caption作为text在页面显示
# user_type_choice = models.BookType.objects.values_list('id', 'caption')
# book_type = forms.CharField(
# widget=forms.widgets.Select(choices=user_type_choice, attrs={'class': "form-control"}))


#写上以下代码就不用担心数据库添加了数据而不能及时获取了
def __init__(self, *args, **kwargs):
#每次创建Form1对象时执行init方法
super(Form1, self).__init__(*args, **kwargs)

self.fields['book_type'] = forms.CharField(
widget=forms.widgets.Select(choices=models.BookType.objects.values_list('id', 'caption'),
attrs={'class': "form-control"}))


HTML:


<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.input-group{
position: relative;
padding: 20px;
width: 250px;
}
.input-group input{
width: 200px;
display: inline-block;
}
.inline-group span{
display: inline-block;
position: absolute;
height: 12px;
font-size: 8px;
border: 1px solid red;
background-color: coral;
color: white;
top: 41px;
left: 20px;
width: 202px;
}
</style>
</head>
<body>
<form action="/form1/" method="POST">
<div class="input-group">
{# 接收后台传过来的form对象,自动生成input标签#}
{{ form.user }}
{# 从后台传过来的error是字典,直接{{ error.user.0 }}呈现错误信息#}
{# 如果后台返回了错误信息,将错误信息放入span标签,在页面显示,否则不显示#}
{% if error.user.0 %}
<span>{{ error.user.0 }}</span>
{% endif %}
</div>
<div class="input-group">
{{ form.pwd }}
{% if error.pwd.0 %}
<span>{{ error.pwd.0 }}</span>
{% endif %}
</div>
<div class="input-group">
{{ form.email }}
{% if error.email.0 %}
<span>{{ error.email.0 }}</span>
{% endif %}
</div>
<div class="input-group">
{{ form.memo }}
{% if error.memo.0 %}
<span>{{ error.memo.0 }}</span>
{% endif %}
</div>
<div class="input-group">
{{ form.book_type }}
{% if error.book_type.0 %}
<span>{{ error.book_type.0 }}</span>
{% endif %}
</div>

<div>
<input type="submit" value="提交" />
</div>
</form>

</body>
</html>


account.py:


from django.shortcuts import render,HttpResponsefrom app01.forms import Form1
from app01.models import *


# def test(req):
# BookType.objects.create(caption='技术')
# BookType.objects.create(caption='文学')
# BookType.objects.create(caption='动漫')
# BookType.objects.create(caption='男人装')
# return HttpResponse("ok")


def form1(request):
if request.method == "POST":
f = Form1(request.POST)
if f.is_valid():
print(f.cleaned_data)
else:
return render(request,"account/form1.html",{"error":f.errors,"form":f})
else:
# 如果不是post提交数据,就不传参数创建对象,并将对象返回给前台,直接生成input标签,内容为空
f = Form1()
return render(request,"account/form1.html",{"form":f})
return render(request,"account/form1.html")


Django里面没有手机验证,没有的需要自定义

示例:

Form

View

标签:form,Python,错误信息,request,Django,forms,models,error
From: https://blog.51cto.com/u_15707053/5947008

相关文章

  • 将Python程序打包成Linux可执行文件
    将Python程序打包成Linux可执行文件安装环境首先我们要安装pip,命令如下:sudoaptinstallpython3-pip使用的工具是pyinstaller,打开终端输入sudopipinstallpyin......
  • python 操作redis有序集合
      https://feeler.blog.csdn.net/article/details/103100452?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogComme......
  • Python requests.post 发送中文 'latin-1' codec can't encode characters in positio
    headers={"Content-type":"application/json;charset=utf-8","Authorization":"bearer"+token}data={#上游任务id名称'upstreamTaskI......
  • Windows下安装mysql-python(MySQLdb)问题记录
    今天太倒霉了,这篇文章马上就要写完了,结果火狐崩溃了,而且csdn居然没有自动保存,只有上午的有记录;想到这个安装的问题也折腾哥快一天了,还是再次打字把问题记录下吧,我就喜欢偏......
  • python处理word、ppt、excel
    介绍采用python_docx模块处理word文档的基本技巧,特别是图片如何提取和写入。 python_docx模块只能处理docx,不支持doc,如需使用,要进行转换。代码入下:fromwin32comimpor......
  • [读书笔记]Python编程:从入门到实践读后感
    0x00前言说句实在话,你买这本书根本就是一个错误。如果,你只是把它束之高阁,就认为自己学会了Python的话。诚如编辑所言,我自己买下这本书已经有一年多了,但真正把它读起来,......
  • Python 导入模块、文件、包、自定义路径包
    测试环境,假设:主文件绝对路径:/home/ubu/py_test/main.py模块文件:/home/ubu/py_test/con.py模块目录:/home/ubu/py_test/modules/tt.py模块目录:/home/ubu/py_test/modules......
  • CMD窗口运行Python脚本颜色字符乱码问题
    Python脚本在CMD窗口运行的时候,可能会出现这种类型的乱码,最开始还以为是哪里的编码出了问题,尝试把cmd的默认字符集改为了utf-8仍然不行。定位一下乱码的字符位置,发现都是......
  • 2.python-练习(日期-函数式编程)
    计算活的天数"""定义函数,根据生日(年月日),计算活了多天"""fromdatetimeimportdatetimedefcalculate_alive_day(year:int,month:int,day:int)->int:......
  • 使用python操作数据库
    importsqlite3conn=sqlite3.connect('mrsoft.db')cursor=conn.cursor()cursor.execute('createtableuser(idint(10)primarykeynamevarchar(20))')cursor.clos......