Form表单——例子
Form
Form的验证思路
前端:form表单
后台:创建form类,当请求到来时,先匹配,匹配出正确和错误信息。
Django的Form验证实例:
创建project,进行基础配置文件配置
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,"static"), )
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
import pymysql pymysql.install_as_MySQLdb()
from django.conf.urls import url from django.contrib import admin from app01.views import accounturlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^form1/', account.form1),
# url(r'^test/', account.test),
]
views.account.py:
from django.shortcuts import render,HttpResponse from app01.forms import Form1def 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()
访问页面:
没有输入内容后提交,通过模板语言展示了错误信息
Django强大之form验证时不用自定义错误信息就可以返回错误信息到前端以标签方式展现。
.is_valid():返回True或者False
.cleaned_data:通过验证后的数据
errors:
.error.get("user",None)error封装所有的错误信息,如果没有获取到,默认为None。
如:
.error.get["pwd"]直接获取到ul、li。
如:
Form之精华版本
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")
注:
页面展示:
注:这里的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 </span>=<span style="color: #000000;"> models.ManyToManyField(Author) book_type </span>= models.ForeignKey(BookType)</pre>
forms.py:
from django import forms from app01 import modelsclass 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 </span>=<span style="color: #000000;"> forms.CharField( widget</span>=<span style="color: #000000;">forms.Textarea() ) </span><span style="color: #008000;">#</span><span style="color: #008000;">直接写数据</span> <span style="color: #008000;">#</span><span style="color: #008000;"> user_type_choice = (</span> <span style="color: #008000;">#</span><span style="color: #008000;"> (0, '普通用户'),</span> <span style="color: #008000;">#</span><span style="color: #008000;"> (1, '高级用户'),</span> <span style="color: #008000;">#</span><span style="color: #008000;"> )</span> <span style="color: #008000;">#</span><span style="color: #008000;">通过BookType表查询信息,values_list拿到的是元组。id作为value显示,caption作为text在页面显示</span> <span style="color: #008000;">#</span><span style="color: #008000;"> user_type_choice = models.BookType.objects.values_list('id', 'caption')</span> <span style="color: #008000;">#</span><span style="color: #008000;"> book_type = forms.CharField(</span> <span style="color: #008000;">#</span><span style="color: #008000;"> widget=forms.widgets.Select(choices=user_type_choice, attrs={'class': "form-control"}))</span> <span style="color: #008000;">#</span><span style="color: #008000;">写上以下代码就不用担心数据库添加了数据而不能及时获取了</span> <span style="color: #0000ff;">def</span> <span style="color: #800080;">__init__</span>(self, *args, **<span style="color: #000000;">kwargs): </span><span style="color: #008000;">#</span><span style="color: #008000;">每次创建Form1对象时执行init方法</span> super(Form1, self).<span style="color: #800080;">__init__</span>(*args, **<span style="color: #000000;">kwargs) self.fields[</span><span style="color: #800000;">'</span><span style="color: #800000;">book_type</span><span style="color: #800000;">'</span>] =<span style="color: #000000;"> forms.CharField( widget</span>=forms.widgets.Select(choices=models.BookType.objects.values_list(<span style="color: #800000;">'</span><span style="color: #800000;">id</span><span style="color: #800000;">'</span>, <span style="color: #800000;">'</span><span style="color: #800000;">caption</span><span style="color: #800000;">'</span><span style="color: #000000;">), attrs</span>={<span style="color: #800000;">'</span><span style="color: #800000;">class</span><span style="color: #800000;">'</span>: <span style="color: #800000;">"</span><span style="color: #800000;">form-control</span><span style="color: #800000;">"</span>}))</pre>
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><span style="color: #0000ff;"><</span><span style="color: #800000;">div</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">input </span><span style="color: #ff0000;">type</span><span style="color: #0000ff;">="submit"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="提交"</span> <span style="color: #0000ff;">/></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">div</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">form</span><span style="color: #0000ff;">></span>
</body>
</html>
account.py:
from django.shortcuts import render,HttpResponse from 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里面没有手机验证,没有的需要自定义
示例:
#!/usr/bin/env python # -*- coding:utf-8 -*- import re from django import forms from django.core.exceptions import ValidationErrordef mobile_validate(value):
mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
if not mobile_re.match(value):
raise ValidationError('手机号码格式错误')class PublishForm(forms.Form):
user_type_choice </span>=<span style="color: #000000;"> ( (0, u</span><span style="color: #800000;">'</span><span style="color: #800000;">普通用户</span><span style="color: #800000;">'</span><span style="color: #000000;">), (</span>1, u<span style="color: #800000;">'</span><span style="color: #800000;">高级用户</span><span style="color: #800000;">'</span><span style="color: #000000;">), ) user_type </span>= forms.IntegerField(widget=forms.widgets.Select(choices=<span style="color: #000000;">user_type_choice, attrs</span>={<span style="color: #800000;">'</span><span style="color: #800000;">class</span><span style="color: #800000;">'</span>: <span style="color: #800000;">"</span><span style="color: #800000;">form-control</span><span style="color: #800000;">"</span><span style="color: #000000;">})) title </span>= forms.CharField(max_length=20<span style="color: #000000;">, min_length</span>=5<span style="color: #000000;">, error_messages</span>={<span style="color: #800000;">'</span><span style="color: #800000;">required</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">标题不能为空</span><span style="color: #800000;">'</span><span style="color: #000000;">, </span><span style="color: #800000;">'</span><span style="color: #800000;">min_length</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">标题最少为5个字符</span><span style="color: #800000;">'</span><span style="color: #000000;">, </span><span style="color: #800000;">'</span><span style="color: #800000;">max_length</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">标题最多为20个字符</span><span style="color: #800000;">'</span><span style="color: #000000;">}, widget</span>=forms.TextInput(attrs={<span style="color: #800000;">'</span><span style="color: #800000;">class</span><span style="color: #800000;">'</span>: <span style="color: #800000;">"</span><span style="color: #800000;">form-control</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">'</span><span style="color: #800000;">placeholder</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">标题5-20个字符</span><span style="color: #800000;">'</span><span style="color: #000000;">})) memo </span>= forms.CharField(required=<span style="color: #000000;">False, max_length</span>=256<span style="color: #000000;">, widget</span>=forms.widgets.Textarea(attrs={<span style="color: #800000;">'</span><span style="color: #800000;">class</span><span style="color: #800000;">'</span>: <span style="color: #800000;">"</span><span style="color: #800000;">form-control no-radius</span><span style="color: #800000;">"</span>, <span style="color: #800000;">'</span><span style="color: #800000;">placeholder</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">详细描述</span><span style="color: #800000;">'</span>, <span style="color: #800000;">'</span><span style="color: #800000;">rows</span><span style="color: #800000;">'</span>: 3<span style="color: #000000;">})) phone </span>= forms.CharField(validators=<span style="color: #000000;">[mobile_validate, ], error_messages</span>={<span style="color: #800000;">'</span><span style="color: #800000;">required</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">手机不能为空</span><span style="color: #800000;">'</span><span style="color: #000000;">}, widget</span>=forms.TextInput(attrs={<span style="color: #800000;">'</span><span style="color: #800000;">class</span><span style="color: #800000;">'</span>: <span style="color: #800000;">"</span><span style="color: #800000;">form-control</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">'</span><span style="color: #800000;">placeholder</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">手机号码</span><span style="color: #800000;">'</span><span style="color: #000000;">})) email </span>= forms.EmailField(required=<span style="color: #000000;">False, error_messages</span>={<span style="color: #800000;">'</span><span style="color: #800000;">required</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">邮箱不能为空</span><span style="color: #800000;">'</span>,<span style="color: #800000;">'</span><span style="color: #800000;">invalid</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">邮箱格式错误</span><span style="color: #800000;">'</span><span style="color: #000000;">}, widget</span>=forms.TextInput(attrs={<span style="color: #800000;">'</span><span style="color: #800000;">class</span><span style="color: #800000;">'</span>: <span style="color: #800000;">"</span><span style="color: #800000;">form-control</span><span style="color: #800000;">"</span>, <span style="color: #800000;">'</span><span style="color: #800000;">placeholder</span><span style="color: #800000;">'</span>: u<span style="color: #800000;">'</span><span style="color: #800000;">邮箱</span><span style="color: #800000;">'</span>}))</pre>
def publish(request): ret = {'status': False, 'data': '', 'error': '', 'summary': ''} if request.method == 'POST': request_form = PublishForm(request.POST) if request_form.is_valid(): request_dict = request_form.clean() print request_dict ret['status'] = True else: error_msg = request_form.errors.as_json() ret['error'] = json.loads(error_msg) return HttpResponse(json.dumps(ret))