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 pymysqlpymysql.install_as_MySQLdb()
from django.conf.urls import urlfrom django.contrib import adminfrom 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,HttpResponsefrom 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:
{#{ { error }}接收后台返回的错误信息封装在ul,li标签里面:#} { { error }}
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:
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 = models.ManyToManyField(Author) book_type = models.ForeignKey(BookType)
forms.py:
from django import formsfrom 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 = 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:
Title
account.py:
from django.shortcuts import render,HttpResponsefrom app01.forms import Form1from 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 refrom django import formsfrom 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 = ( (0, u'普通用户'), (1, u'高级用户'), ) user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice, attrs={ 'class': "form-control"})) title = forms.CharField(max_length=20, min_length=5, error_messages={ 'required': u'标题不能为空', 'min_length': u'标题最少为5个字符', 'max_length': u'标题最多为20个字符'}, widget=forms.TextInput(attrs={ 'class': "form-control", 'placeholder': u'标题5-20个字符'})) memo = forms.CharField(required=False, max_length=256, widget=forms.widgets.Textarea(attrs={ 'class': "form-control no-radius", 'placeholder': u'详细描述', 'rows': 3})) phone = forms.CharField(validators=[mobile_validate, ], error_messages={ 'required': u'手机不能为空'}, widget=forms.TextInput(attrs={ 'class': "form-control", 'placeholder': u'手机号码'})) email = forms.EmailField(required=False, error_messages={ 'required': u'邮箱不能为空','invalid': u'邮箱格式错误'}, widget=forms.TextInput(attrs={ 'class': "form-control", 'placeholder': u'邮箱'}))
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))