django ---forms组件
forms组件
本文目录
1 校验字段功能
针对一个实例:注册用户讲解。
模型:models.py
class UserInfo(models.Model):
name=models.CharField(max_length=32)
pwd=models.CharField(max_length=32)
email=models.EmailField( 模版文件
复制代码 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title> </head>
<body> <form action="" method="post">
{% csrf_token %}
<div>
<label for="user">用户名</label>
<p><input type="text" name="name" id="name"></p>
</div>
<div>
<label for="pwd">密码</label>
<p><input type="password" name="pwd" id="pwd"></p>
</div>
<div>
<label for="r_pwd">确认密码</label>
<p><input type="password" name="r_pwd" id="r_pwd"></p>
</div>
<div>
<label for="email">邮箱</label>
<p><input type="text" name="email" id="email"></p>
</div>
<input type="submit">
</form> </body>
</html>
视图函数:
# forms组件
from django.forms import widgets wid_01=widgets.TextInput(attrs={"class":"form-control"})
wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) class UserForm(forms.Form):
name=forms.CharField(max_length=32,
widget=wid_01
)
pwd=forms.CharField(max_length=32,widget=wid_02)
r_pwd=forms.CharField(max_length=32,widget=wid_02)
email=forms.EmailField(widget=wid_01)
tel=forms.CharField(max_length=32,widget=wid_01) def register(request): if request.method=="POST":
form=UserForm(request.POST)
if form.is_valid():
print(form.cleaned_data) # 所有干净的字段以及对应的值
else:
print(form.cleaned_data) #
print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]}
print(form.errors.get("name")) # ErrorList ["错误信息",]
return HttpResponse("OK")
form=UserForm()
return render(request,"register.html",locals())
2 渲染标签功能
渲染方式1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h3>注册页面</h3>
<div class="container">
<div class="row">
<div class="col-md-6 col-lg-offset-3"> <form action="" method="post">
{% csrf_token %}
<div>
<label for="">用户名</label>
{{ form.name }}
</div>
<div>
<label for="">密码</label>
{{ form.pwd }}
</div>
<div>
<label for="">确认密码</label>
{{ form.r_pwd }}
</div>
<div>
<label for=""> 邮箱</label>
{{ form.email }}
</div> <input type="submit" class="btn btn-default pull-right">
</form>
</div>
</div>
</div> </body>
</html>
渲染方式2
<form action="" method="post">
{% csrf_token %} {% for field in form %}
<div>
<label for="">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
<input type="submit" class="btn btn-default pull-right"> </form>
渲染方式3
<form action="" method="post">
{% csrf_token %} {{ form.as_p }}
<input type="submit" class="btn btn-default pull-right"> </form>
3 渲染错误信息功能
视图
def register(request): if request.method=="POST":
form=UserForm(request.POST)
if form.is_valid():
print(form.cleaned_data) # 所有干净的字段以及对应的值
else:
print(form.cleaned_data) #
print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]}
print(form.errors.get("name")) # ErrorList ["错误信息",]
return render(request,"register.html",locals())
form=UserForm()
return render(request,"register.html",locals())
模板
<form action="" method="post" novalidate>
{% csrf_token %} {% for field in form %}
<div>
<label for="">{{ field.label }}</label>
{{ field }} <span class="pull-right" style="color: red">{{ field.errors.0 }}</span>
</div>
{% endfor %}
<input type="submit" class="btn btn-default"> </form>
4 组件的参数配置
class Ret(Form):
name = forms.CharField(max_length=10, min_length=2, label='用户名',
error_messages={'required': '该字段不能为空', 'invalid': '格式错误', 'max_length': '太长',
'min_length': '太短'},
widget=widgets.TextInput(attrs={'class':'form-control'}))
pwd = forms.CharField(max_length=10, min_length=2, widget=widgets.PasswordInput(attrs={'class':'form-control'}))
email = forms.EmailField(label='邮箱', error_messages={'required': '该字段不能为空', 'invalid': '格式错误'})
5 局部钩子
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
def clean_name(self): val=self.cleaned_data.get("name") ret=UserInfo.objects.filter(name=val) if not ret:
return val
else:
raise ValidationError("该用户已注册!") def clean_tel(self): val=self.cleaned_data.get("tel") if len(val)==11: return val
else:
raise ValidationError("手机号格式错误")
6 全局钩子
def clean(self):
pwd=self.cleaned_data.get('pwd')
r_pwd=self.cleaned_data.get('r_pwd') if pwd and r_pwd:
if pwd==r_pwd:
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')
else: return self.cleaned_data
pwd_err=my_form.errors.get('__all__')
from django import forms from django.forms import widgets
from app01.models import UserInfo from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class UserForm(forms.Form):
name=forms.CharField(min_length=4,label="用户名",error_messages={"required":"该字段不能为空"},
widget=widgets.TextInput(attrs={"class":"form-control"})
)
pwd=forms.CharField(min_length=4,label="密码",
widget=widgets.PasswordInput(attrs={"class":"form-control"})
)
r_pwd=forms.CharField(min_length=4,label="确认密码",error_messages={"required":"该字段不能为空"},widget=widgets.TextInput(attrs={"class":"form-control"}))
email=forms.EmailField(label="邮箱",error_messages={"required":"该字段不能为空","invalid":"格式错误"},widget=widgets.TextInput(attrs={"class":"form-control"}))
tel=forms.CharField(label="手机号",widget=widgets.TextInput(attrs={"class":"form-control"})) def clean_name(self): val=self.cleaned_data.get("name") ret=UserInfo.objects.filter(name=val) if not ret:
return val
else:
raise ValidationError("该用户已注册!") def clean_tel(self): val=self.cleaned_data.get("tel") if len(val)==11: return val
else:
raise ValidationError("手机号格式错误") def clean(self):
pwd=self.cleaned_data.get('pwd')
r_pwd=self.cleaned_data.get('r_pwd') if pwd and r_pwd:
if pwd==r_pwd:
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')
else: return self.cleaned_data
myforms
from django.shortcuts import render,HttpResponse # Create your views here. from app01.myforms import * def reg(request): if request.method=="POST": print(request.POST) #form=UserForm({"name":"yu","email":"123@qq.com","xxxx":"alex"}) form=UserForm(request.POST) # form表单的name属性值应该与forms组件字段名称一致 print(form.is_valid()) # 返回布尔值 if form.is_valid():
print(form.cleaned_data) # {"name":"yuan","email":"123@qq.com"}
else:
print(form.cleaned_data) # {"email":"123@qq.com"}
# print(form.errors) # {"name":[".........."]}
# print(type(form.errors)) # ErrorDict
# print(form.errors.get("name"))
# print(type(form.errors.get("name"))) # ErrorList
# print(form.errors.get("name")[0]) # 全局钩子错误
#print("error",form.errors.get("__all__")[0])
errors=form.errors.get("__all__") return render(request,"reg.html",locals()) ''' form.is_valid() :返回布尔值
form.cleaned_data :{"name":"yuan","email":"123@qq.com"}
form.errors :{"name":[".........."]} ''' form=UserForm() return render(request,"reg.html",locals())
视图函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.error{
color: red;
}
</style>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body> <div class="container"> <div class="row">
<div class="col-md-6 col-lg-offset-3"> {#<h3>简单form</h3>#}
{##}
{##}
{#<form action="" method="post" novalidate>#}
{# {% csrf_token %}#}
{# <p>用户名<input type="text" name="name"></p>#}
{# <p>密码 <input type="text" name="pwd"></p>#}
{# <p>确认密码 <input type="text" name="r_pwd"></p>#}
{# <p>邮箱 <input type="text" name="email"></p>#}
{# <p>手机号 <input type="text" name="tel"></p>#}
{# <input type="submit">#}
{##}
{#</form>#} <hr>
<h3>forms组件渲染方式1</h3>
<form action="" method="post" novalidate> {% csrf_token %}
<p>{{ form.name.label }}
{{ form.name }} <span class="pull-right error">{{ form.name.errors.0 }}</span>
</p>
<p>{{ form.pwd.label }}
{{ form.pwd }} <span class="pull-right error">{{ form.pwd.errors.0 }}</span>
</p>
<p>确认密码
{{ form.r_pwd }} <span class="pull-right error">{{ form.r_pwd.errors.0 }}</span><span class="pull-right error">{{ errors.0 }}</span>
</p>
<p>邮箱 {{ form.email }} <span class="pull-right error">{{ form.email.errors.0 }}</span></p>
<p>手机号 {{ form.tel }} <span class="pull-right error">{{ form.tel.errors.0 }}</span></p>
<input type="submit"> </form> {#<h3>forms组件渲染方式2</h3>#}
{##}
{#<form action="" method="post" novalidate>#}
{# {% csrf_token %}#}
{##}
{# {% for field in form %}#}
{##}
{# <div>#}
{# <label for="">{{ field.label }}</label>#}
{# {{ field }}#}
{# </div>#}
{##}
{# {% endfor %}#}
{##}
{# <input type="submit">#}
{#</form>#}
{##}
{#<h3>forms组件渲染方式3</h3>#}
{##}
{#<form action="" method="post">#}
{# {% csrf_token %}#}
{##}
{# {{ form.as_p }}#}
{##}
{# <input type="submit">#}
{#</form>#} </div>
</div>
</div> </body>
</html>
模版文件
------------https://www.cnblogs.com/liuqingzheng/articles/9509775.html
django ---forms组件的更多相关文章
- Django forms组件里的ChoiceField、ModelChoiceField和ModelMutipleChoiceField的区别
阅读简要 首先我们要明白Django forms组件里的ChoiceField.ModelChoiceField和ModelMutipleChoiceField是继承关系 ChoiceField 1. ...
- python django(forms组件)
forms组件最大的作用,就是做数据校验. 普通做法,一个一个写校验规则,没有解耦.校验规则,都在视图函数里面. 网页校验 修改urls.py,增加路径addbook from app01 impor ...
- Django forms组件与钩子函数
目录 一.多对多的三种创建方式 1. 全自动 2. 纯手撸(了解) 3. 半自动(强烈推荐) 二.forms组件 1. 如何使用forms组件 2. 使用forms组件校验数据 3. 使用forms组 ...
- Django forms组件的校验
引入: from django import forms 使用方法:定义规则,例: class UserForm(forms.Form): name=forms.CharField(max_lengt ...
- Django学习之八:forms组件【对form舒心了】
目录 Django forms组件 bound and unbound form instance forms渲染有关 隐藏一个字段,不渲染它 form 校验 form类 ModelForm 利用Mo ...
- Django-多对多关系的三种创建方式-forms组件使用-cookie与session-08
目录 表模型类多对多关系的三种创建方式 django forms 组件 登录功能手写推理过程 整段代码可以放过来 forms 组件使用 forms 后端定义规则并校验结果 forms 前端渲染标签组件 ...
- Django组件-Forms组件
Django的Forms组件主要有以下几大功能: 页面初始化,生成HTML标签 校验用户数据(显示错误信息) HTML Form提交保留上次提交数据 一.小试牛刀 1.定义Form类 from dja ...
- Django组件--forms组件(注册用)
一.forms组件--校验类的使用 二.form组件--校验类的参数 三.forms组件校验的局部钩子--自定义校验规则(要看源码理解) 四.forms组件校验的全局钩子--校验form表单两次密码输 ...
- web框架开发-Django的Forms组件
校验字段功能 针对一个实例:用户注册. 模型:models.py class UserInfo(models.Model): name=models.CharField(max_length=32) ...
随机推荐
- 如何用iptables实现NAT(转)
http://www.cnblogs.com/little-ant/p/3548087.html
- 枚举,Math和Random
1.实用类: 01.枚举 enum Student stu=new Student(); 我们为了保证用户一个健康的输入! 我们使用了封装特性! 用户就不能直接访问我们的属性了!! private c ...
- Docker安装websphere(四)
在Docker容器里安装webshpere <!--前提:已经安装好了docker,能够正常使用.--> (1)docker安装websphere(需要账号和密码登录,不挂载数据卷) 获取 ...
- jenkins使用jacoco插件检测代码覆盖率(八)
代码覆盖率:类覆盖,方法覆盖,行覆盖,指令覆盖……(简而言之,就是判断有没有被执行) 覆盖率 = 已经执行的代码 / 总代码 (1)创建maven项目,配置pom.xml如下 pom.xml < ...
- PC/FORTH 编辑程序
body, table{font-family: 微软雅黑} table{border-collapse: collapse; border: solid gray; border-width: 2p ...
- session会话示例
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"% ...
- 玩转X-CTR100 | STM32F4 l X-Assistant串口助手控制功能
我造轮子,你造车,创客一起造起来!塔克创新资讯[塔克社区 www.xtark.cn ][塔克博客 www.cnblogs.com/xtark/ ] X-CTR100控制器配套的X-Assis ...
- 201621123001《Java程序设计》第1周学习总结
1. 本周学习总结 认识java的三个层次:java语法 面向对象设计能力 应用 . 学习eclipse创建java文件的方法. 学习markdown的基本语法,了解写博客的几种常用形式. 了解JVM ...
- quartz自定义线程数
1.加载包 2.添加quartz.propertes 3.编写自己的任务类 4.添加自动任务配置 5.通过 quartzProperties 配置连接池 1.加载包 <dependency> ...
- SharePoint online Multilingual support - Settings
博客地址:http://blog.csdn.net/FoxDave This post will talk about how to enable sharepoint online site mul ...