django中forms组件的使用与注意
作者:lemon 时间:2021-03-11 00:14:04
forms组件
django框架提供了一个Form类,来进行web开发中的表单提交数据的处理工作。
导入相关模块
from django import forms
from django.forms import fields
常规使用
class F1Form(forms.Form):
username = fields.CharField(max_length=18,min_length=2,required=True)
pwd = fields.CharField(required=True,max_length=16,min_length=6)
age = fields.IntegerField(required=True)
email = fields.EmailField(required=True)
自定义错误信息error_messages
class F1Form(forms.Form):
username = fields.CharField(max_length=18,
min_length=6,
required=True,
error_messages={
'required':'用户名不能为空',
'min_length':'用户名过短',
'max_length':'用户名过长'
}
)
html的调用
views部分:
def rege(req):
obj = F1Form()
return render(req,'rege.html',{'OBJ':obj})
html部分:
<form action="">
<p>{{ OBJ.username }}</p>
<p>{{ OBJ.pwd }}</p>
<p>{{ OBJ.age }}</p>
<p>{{ OBJ.email }}</p>
</form>
后台数据验证:
obj = F1Form(req.POST)
if obj.is_valid(): #判断传来的值是否通过验证
models.UserInfo.objects.create(**obj.cleaned_data) #将值写入数据库
~需要注意的是create(**obj.cleaned_data)
方法写入数据库的方式,是在forms提交的name名跟数据库的一致才可以.
来源:https://segmentfault.com/a/1190000019668281
标签:django,forms,组件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
ORACLE 如何查询被锁定表及如何解锁释放session
2023-07-02 11:59:39
asp如何做一个看他爱不爱你的小测验?
2010-07-11 21:16:00
Python中文分词库jieba,pkusegwg性能准确度比较
2021-12-17 13:05:41
![](https://img.aspxhome.com/file/2023/6/78616_0s.png)
[精品]ASP中常用的22个FSO文件操作函数
2007-08-18 15:12:00
![](https://img.aspxhome.com/file/UploadPic/up/2007081816282483.jpg)
PHP获取类私有属性的3种方法
2023-11-20 10:32:16
![](https://img.aspxhome.com/file/2023/6/106296_0s.jpg)
Python TypeError: ‘float‘ object is not subscriptable错误解决
2023-09-13 05:33:02
![](https://img.aspxhome.com/file/2023/9/62249_0s.png)
如何取得表中字段的属性?
2010-01-18 20:52:00
sqlserver数据库主键的生成方式小结(sqlserver,mysql)
2012-08-21 10:25:45
Python实现读取文件夹按数字排序功能
2023-08-24 02:12:45
Python使用GitPython操作Git版本库的方法
2021-04-28 07:22:16
python的random和time模块详解
2023-07-27 18:16:27
![](https://img.aspxhome.com/file/2023/5/61215_0s.png)
十分钟利用Python制作属于你自己的个性logo
2021-08-25 05:12:41
![](https://img.aspxhome.com/file/2023/2/80762_0s.jpg)
selenium+python自动化测试之使用webdriver操作浏览器的方法
2023-06-28 03:04:47
如何禁止搜索引擎收录你的网站
2008-10-20 12:57:00
python扫描proxy并获取可用代理ip的实例
2023-07-29 16:42:50
浅谈Django中的QueryDict元素为数组的坑
2023-08-22 18:55:54
![](https://img.aspxhome.com/file/2023/8/62588_0s.jpg)
如何解决django配置settings时遇到Could not import settings 'conf.local'
2021-07-23 13:31:57
详解Python静态网页爬取获取高清壁纸
2023-10-18 08:27:42
![](https://img.aspxhome.com/file/2023/4/63214_0s.png)
python用10行代码实现对黄 色图片的检测功能
2023-11-16 23:48:33
关于window.opener的用法
2008-02-23 11:03:00