首页 > 代码库 > Django进阶之Form
Django进阶之Form
Form的验证思路
前端:form表单
后台:创建form类,当请求到来时,先匹配,匹配出正确和错误信息。
Django的Form验证实例:
创建project,进行基础配置文件配置
settings.py:
STATIC_URL = ‘/static/‘ STATICFILES_DIRS = ( os.path.join(BASE_DIR,"static"), )
settings.py之csrf注销
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‘, ]
__init__.py:
import pymysql pymysql.install_as_MySQLdb()
urls.py:
from django.conf.urls import url from django.contrib import admin from app01.views import account urlpatterns = [ 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 Form1 def 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="http://www.mamicode.com/提交" /> </div> </form> </body>
forms.py:
from django import forms class 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 forms class 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="http://www.mamicode.com/提交" /> </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 models class 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="http://www.mamicode.com/提交" /> </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:
#!/usr/bin/env python # -*- coding:utf-8 -*- import re from django import forms from django.core.exceptions import ValidationError def 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‘邮箱‘}))
View
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))
Django进阶之Form
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。