1 简单的校验字段功能
views
from django.shortcuts import render, HttpResponse from django import forms class MyForm(forms.Form): name = forms.CharField(max_length=8, min_length=3) pwd = forms.CharField(max_length=8, min_length=3) email = forms.EmailField() # Create your views here. def index_form(request): # 生成对象是实例化,传入要校验的数据(字典) dic = {'name': 'andy', 'pwd': '13', 'email': '11@qq.com'} myform = MyForm(dic) if myform.is_valid(): # 校验通过的数据 print(myform.cleaned_data) return HttpResponse('校验成功') else: print(myform.cleaned_data) # 错误的信息,他是一个字典 print(myform.errors) print(type(myform.errors)) return HttpResponse('校验失败')
2 数据从前端传过来校验
views
from django import forms class MyForm(forms.Form): name = forms.CharField(max_length=8, min_length=3) pwd = forms.CharField(max_length=8, min_length=3) email = forms.EmailField() # Create your views here. def index_form(request): # 生成对象是实例化,传入要校验的数据(字典) if request.method == 'GET': return render(request, 'index.html') elif request.method == 'POST': myform = MyForm(request.POST) if myform.is_valid(): # 校验通过的数据 print(myform.cleaned_data) return HttpResponse('校验成功') else: print(myform.cleaned_data) # 错误的信息,他是一个字典 print(myform.errors) print(type(myform.errors)) return HttpResponse('校验失败')
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> <p>用户名: <input type="text" name="name"></p> <p>密码: <input type="text" name="pwd"></p> <p>邮箱: <input type="text" name="email"></p> <input type="submit" value="提交"> </form> </body> </html>
3 渲染标签功能
views
from django import forms class MyForm(forms.Form): name = forms.CharField(max_length=8, min_length=3,label='用户名') pwd = forms.CharField(max_length=8, min_length=3,label='密码') email = forms.EmailField(label='邮箱') def index_form(request): # 生成对象是实例化,传入要校验的数据(字典) myform=MyForm() if request.method == 'GET': return render(request, 'index2.html',locals())
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>第一种方式</h1> <form action="" method="post"> <p>用户名: {{ myform.name }}</p> <p>密码: {{ myform.pwd }}</p> <p>邮箱: {{ myform.email }}</p> <input type="submit" value="提交"> </form> <h1>第二种方式</h1> <form action="" method="post"> {% for foo in myform %} <p>{{ foo.label }}:{{ foo }}</p> {% endfor %} <h1>第三种方式(不建议用)</h1> <form action="" method="post" > {# {{ myform.as_p }}#} {{ myform.as_ul }} <input type="submit" value="提交"> <input type="submit" value="提交"> </form> </body> </html>
4 渲染错误信息,渲染页面
-渲染错误信息 - myforms有errors -属性(name)也有errors -错误信息,变成中文: - error_messages={'max_length': '最长是8', 'min_length': '最短是3', 'required': '这个必须填','invalid': '不符合邮箱格式'} -给input标签指定样式,指定格式: -widget=widgets.TextInput(attrs={'class':'form-control'}) -模板,渲染错误信息:<span>{{ myform.name.errors.0 }}</span>
views
from django.shortcuts import render, HttpResponse,redirect # forms组件数据校验的功能 # 第一步:先要继承Form from django import forms from django.forms import widgets from django.core.exceptions import ValidationError # 写一个类 class MyForm(forms.Form): # 定义一个属性,可以用来校验字符串类型 # 限制最大长度是8,最小长度是3 name = forms.CharField(max_length=8, min_length=3, label='用户名', error_messages={'max_length': '最长是8', 'min_length': '最短是3', 'required': '这个必须填'}, widget=widgets.TextInput(attrs={'class': 'form-control'})) pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码', error_messages={'max_length': '最长是8', 'min_length': '最短是3', 'required': '这个必须填'}, widget=widgets.PasswordInput()) re_pwd = forms.CharField(max_length=8, min_length=3, required=True, label='确认密码', error_messages={'max_length': '最长是8', 'min_length': '最短是3', 'required': '这个必须填'}, widget=widgets.PasswordInput()) # 校验是否是邮箱格式 email = forms.EmailField(label='邮箱', error_messages={'required': '这个必须填', 'invalid': '不符合邮箱格式'}) def index_form(request): # 生成对象是实例化,传入要校验的数据(字典) myform = MyForm() if request.method == 'GET': return render(request, 'index3.html', locals()) elif request.method=='POST': myform=MyForm(request.POST) return render(request, 'index3.html', locals())
index.html
<form action="" method="post" novalidate> {% for foo in myform %} <p>{{ foo.label }}:{{ foo }} {{ foo.errors.0 }} </p> {% endfor %} <input type="submit" value="提交" ><span>{{ all_error }}</span> </form>
5 局部钩子校验
-定义一个函数,名字叫:clean_字段名字,内部,取出该字段,进行校验,如果通过,将该字段返回,如果失败,抛异常(ValidationError)
from django.core.exceptions import ValidationError #在类calss MyForm(forms.Form):里面写 def clean_name(selef): # self为当前form对象 name=self.cleaned_data.get('name) if name.startswith('sb'): #失败,报异常 raise ValidationError('不能以傻逼开头') #正常,就返回name return name
6 全局钩子校验
views
#重写clean方法,在类MyForm中 def clean(self): #程序能走到该函数,前面校验已经通过了,所以可以从cleaned_data中取出密码和确认密码 pwd=self.cleaned_data.get('pwd') re_pwd=self.cleaned_data.get('re_pwd') #进行自己的校验 if pwd==re_pwd: #通过,直接返回cleaned_data return self.cleaned_data else: #失败,抛异常(ValidationError) raise ValidationError('两次密码不一致')
#在类MyFor外 def index_form(request): # 生成对象是实例化,传入要校验的数据(字典) if request.method == 'GET': myform = MyForm() elif request.method == 'POST': myform = MyForm(request.POST) if myform.is_valid(): print(myform.cleaned_data) else: all_errors=myform.errors.get('__all__') print(myform.errors.as_data) return render(request, 'index3.html', locals())
index.html
<form action="" method="post" novalidate> {% for foo in myform %} <p>{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></p> {% endfor %} <input type="submit" value="提交"><span>{{ all_errors }}</span> </form>
7 form表单提交注册功能
views
from django.shortcuts import render, HttpResponse, redirect
from app01 import models
from django.core.exceptions import ValidationError
from django import forms
from django.forms import widgets
# Create your views here.
class MyForm(forms.Form):
name = forms.CharField(max_length=8, min_length=3, label='用户名',
error_messages={'max_length': '最长是8', 'min_length': '最短是3', 'required': '这个必须填'},
widget=widgets.TextInput(attrs={'class': 'form-control','style':'color=red' }))
pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码',
error_messages={'max_length': '最长是8', 'min_length': '最短是3', 'required': '这个必须填'},
widget=widgets.PasswordInput(attrs={'class': 'form-control'}))
re_pwd = forms.CharField(max_length=8, min_length=3, required=True, label='确认密码',
error_messages={'max_length': '最长是8', 'min_length': '最短是3', 'required': '这个必须填'},
widget=widgets.PasswordInput(attrs={'class': 'form-control'}))
# 校验是否是邮箱格式
email = forms.EmailField(label='邮箱', error_messages={'required': '这个必须填', 'invalid': '不符合邮箱格式'},
widget=widgets.EmailInput(attrs={'class': 'form-control'}))
def clean_name(self):
name = self.cleaned_data.get('name')
name1 = models.User.objects.filter(name=name)
if name1:
raise ValidationError('%s已经存在,请更换用户名'%name)
else:
return name
def clean(self):
pwd = self.cleaned_data.get('pwd')
re_pwd = self.cleaned_data.get('re_pwd')
if pwd == re_pwd:
# 这是什么,下面返回的又是什么
print(self.cleaned_data)
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')
def index(request):
if request.method == 'GET':
myform = MyForm()
elif request.method == 'POST':
myform = MyForm(request.POST)
if myform.is_valid():
print(myform.cleaned_data)
myform.cleaned_data.pop('re_pwd')
models.User.objects.create(**myform.cleaned_data)
return redirect('https://www.baidu.com')
else:
all_error = myform.errors.get('__all__')
print(all_error)
if all_error:
all_error = all_error[0]
return render(request, 'index.html', locals())
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="/static/jquery-3.3.1.js"></script>
<title>Title</title>
</head>
<body>
<h1 style="text-align: center">用户注册</h1>
<form action="" method="post" novalidate class="col-md-6 col-md-offset-3 " >
{% for foo in myform %}
<p style=" text-align:center;font:normal 10px/30px 'STSong">{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></p>
{% endfor %}
<button id="btn">提交</button>
</form>
</body>
</html>
model
from django.db import models # Create your models here. class User(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) email=models.EmailField()