Form
Form的验证思路
前端:form表单
后台:创建form类,当请求到来时,先匹配,匹配出正确和错误信息。
Django的Form验证实例:
创建project,进行基础配置文件配置
settings.py
settings.py之csrf注销
__init__.py
urls.py
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。
如:
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 = models.ManyToManyField(Author)book_type = models.ForeignKey(BookType)
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 = 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:
<!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><div><input type="submit" value="提交" /></div></form></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里面没有手机验证,没有的需要自定义
示例:
Form
View