一 forms组件css
-forms是什么? 就是一个类,能够校验字段(前台传过来的字段) -怎么用: -校验字段功能: -先写一个类,继承Form from django.shortcuts import render, HttpResponse from django import forms # 写一个类,要校验那些字段,就是类的属性 class MyForm(forms.Form): # 定义一个属性,能够用来校验字符串类型 # 限制最大长度是8,最小长度是3 name=forms.CharField(max_length=8,min_length=3) pwd=forms.CharField(max_length=8,min_length=3,required=True) # 校验是不是邮箱格式 email=forms.EmailField() -使用: #实例化产生对象,传入要校验的数据(字典) myform=MyForm(request.POST) # is_valid若是是true表示校验成功,反之,校验失败 if myform.is_valid(): # 校验经过的数据 print(myform.cleaned_data) return HttpResponse('校验成功') else: print(myform.cleaned_data) #校验失败的信息 print(myform.errors) -注意:校验的字段,能够多,可是不能少
二 渲染模板html
第一中方式:(灵活性最高) <form action="" method="post" > <p>用户名: {{ myform.name }}</p> <p>密码: {{ myform.pwd }}</p> <p>邮箱: {{ myform.email }}</p> <input type="submit" value="提交"> </form> 第二种方式:for循环form对象(用的比较多): <form action="" method="post" > {% for foo in myform %} <p>{{ foo.label }}:{{ foo }}</p> {% endfor %} <input type="submit" value="提交"> </form> 第三种方式(不建议用): <form action="" method="post" > {#{{ myform.as_p }}#} {{ myform.as_ul }} <input type="submit" value="提交"> </form>
三 渲染错误信息jquery
- 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>
四 局部钩子与全局钩子django
-局部钩子校验 -定义一个函数,名字叫:clean_字段名字,内部,取出该字段,进行校验,若是经过,将该字段返回,若是失败,抛异常(ValidationError) def clean_name(self): # self:当前form对象 name = self.cleaned_data.get('name') if name.startswith('sb'): # 失败,抛异常 raise ValidationError('名字不能以傻逼开头') if models.User.objects.filter(name=name).first(): raise ValidationError('此用户名已被使用') return name -全局钩子 #重写clean方法 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('两次密码不一致')
五 注册bootstrap


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) phone = models.CharField(max_length=32) email = models.EmailField()


<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css"> <script src="/static/bootstrap-3.3.7-dist/js/jquery-3.3.1.min.js"></script> <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.js"></script> <title>Title</title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-3"> <form action="" method="post" class="form-horizontal" novalidate> <div class="form-group"> {% for foo in myform %} <label for="inputEmail3" class="col-sm-4 control-label">{{ foo.label }}:</label> <div class="col-sm-8"><p>{{ foo }} <span style="color: red">{{ foo.errors.0 }}</span></p></div> {% endfor %} <input type="submit" value="注册" class="col-md-offset-7 btn btn-primary"><span style="color: red">{{ all_error }}</span> </div> </form> </div> </div> </div> </body> </html>


from django.shortcuts import render, redirect, HttpResponse from django.http import JsonResponse from app01 import models from django import forms from django.forms import widgets from django.core.exceptions import ValidationError # 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', 'id': 'name'})) pwd = forms.CharField(max_length=16, min_length=6, label='密码', error_messages={'max_length': '密码最长是16位', 'min_length': '用户名最短是6位', 'required': '此项为必填项'}, widget=widgets.PasswordInput(attrs={'class': 'form-control', 'id': 'pwd'})) re_pwd = forms.CharField(max_length=16, min_length=6, label='确认密码', error_messages={'max_length': '密码最长是16位', 'min_length': '用户名最短是6位', 'required': '此项为必填项'}, widget=widgets.PasswordInput(attrs={'class': 'form-control', 'id': 're_pwd'})) phone = forms.CharField(label='手机号', error_messages={'required': '此项为必填项'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'id': 'phone'})) email = forms.EmailField(label='邮箱', widget=widgets.TextInput(attrs={'class': 'form-control', 'id': 'email'}), error_messages={'required': '此项为必填项', 'invalid': '不符合邮箱格式'}) def clean_name(self): name = self.cleaned_data.get('name') if name.startswith('sb'): raise ValidationError('名字不能以傻逼开头') if models.User.objects.filter(name=name).first(): raise ValidationError('此用户名已被使用') return name def clean_phone(self): phone = self.cleaned_data.get('phone') if models.User.objects.filter(phone=phone).first(): raise ValidationError('此号码已被注册过,请更换号码') if len(phone) != 11: raise ValidationError('请填写正确的手机号') return phone def clean_email(self): email = self.cleaned_data.get('phone') if models.User.objects.filter(email=email).first(): raise ValidationError('此邮箱已被注册过,请更换邮件') return email def clean(self): pwd = self.cleaned_data.get('pwd') re_pwd = self.cleaned_data.get('re_pwd') if pwd == re_pwd: return self.cleaned_data else: raise ValidationError('两次密码不一致') def index(request): if request.method == 'GET': myform = MyForm() if request.method == 'POST': myform = MyForm(request.POST) if myform.is_valid(): myform.cleaned_data.pop('re_pwd') models.User.objects.create(**myform.cleaned_data) return redirect('http://baidu.com') else: all_error = myform.errors.get('__all__') if all_error: all_error = all_error[0] return render(request, 'index.html', locals())