django_forms
forms组件简化了前端编写,django通过forms组件实现前端样式的构建、渲染与校验。
效果图:
forms组件
from django.forms import widgets from django import forms from django.core.exceptions import ValidationError wdg1 = widgets.TextInput(attrs={'class':'form-control'}) # 可以给input标签加任何属性 wdg2 = widgets.PasswordInput(attrs={'class':'form-control'}) class UserForms(forms.Form): # 创建forms校验对象 name = forms.CharField(min_length=4, max_length=8,widget=wdg1, label='姓名') # min_length 校验规则 pwd = forms.CharField(min_length=4,widget=wdg2, label='密码') r_pwd = forms.CharField(min_length=4,widget=wdg2, label='确认密码') email = forms.EmailField(widget=wdg1, label='邮箱') tel = forms.CharField(min_length=11, max_length=11,widget=wdg1, label='手机号') #局部钩子 def clean_name(self): val = self.cleaned_data.get('name') if not val.isdigit(): return val else: raise ValidationError('用户名不能全是数字') # 全局钩子 def clean(self): pwd = self.cleaned_data.get('pwd') r_pwd = self.cleaned_data.get('r_pwd') if pwd == r_pwd: return self.cleaned_data else: raise ValidationError('两次密码不一致!')
视图函数
1 from django.shortcuts import render 2 from django.forms import widgets 3 from django import forms 4 5 # Create your views here. 6 7 8 # 简单的forms校验 9 def simple_forms(request): 10 class UserForms(forms.Form): # 创建forms校验对象 11 name = forms.CharField(min_length=4, max_length=8) # min_length 校验规则 12 pwd = forms.CharField(min_length=4) 13 r_pwd = forms.CharField(min_length=4) 14 email = forms.EmailField() 15 tel = forms.CharField(min_length=11, max_length=11) 16 if request.method == 'POST': 17 res = UserForms(request.POST) 18 print(res) 19 print(res.is_valid()) # 规则是否校验通过 全部通过为True 20 if res.is_valid(): 21 # cleaned_data 校验通过的所有字段,比如输入100个字段,但是这里只校验4个字段,得到的就是过滤后的4个字段 22 print(res.cleaned_data) 23 else: 24 print(res.cleaned_data) # 通过的部分字段,哪个字段校验通过就往这里加 25 print(res.errors) # ErrorDict : {"校验错误的字段":["错误信息",]} 不通过的往这里加,是一个字典 26 print(res.errors.get('email')) # ErrorList ["错误信息",] 是一个列表 27 print(res.errors.get('email')[0]) # 取第一个错误信息,一般都是取第一个错误信息返回给前端 28 return render(request, 'simple_forms.html') 29 30 31 # forms校验 前端渲染 为了避免前端和后端字段不一致,可以直接由后端渲染前端页面 32 def multi_forms(request): 33 wdg1 = widgets.TextInput(attrs={'class':'form-control'}) # 可以给input标签加任何属性 34 wdg2 = widgets.PasswordInput(attrs={'class':'form-control'}) 35 class UserForms(forms.Form): # 创建forms校验对象 36 name = forms.CharField(min_length=4, max_length=8,widget=wdg1, label='姓名') # min_length 校验规则 37 pwd = forms.CharField(min_length=4,widget=wdg2, label='密码') 38 r_pwd = forms.CharField(min_length=4,widget=wdg2, label='确认密码') 39 email = forms.EmailField(widget=wdg1, label='邮箱') 40 tel = forms.CharField(min_length=11, max_length=11,widget=wdg1, label='手机号') 41 myform = UserForms() # 实例传给前端进行渲染 42 if request.method == 'POST': 43 # 将这个传给前端,可以渲染错误提示信息 myform.tel.errors.0 拿到相应字段的错误信息进行渲染 44 # 而且将用户输入的信息重传给用户 避免待提交的数据刷新 45 myform = UserForms(request.POST) 46 print(myform) 47 print(myform.is_valid()) # 规则是否校验通过 全部通过为True 48 if myform.is_valid(): 49 # cleaned_data 校验通过的所有字段,比如输入100个字段,但是这里只校验4个字段,得到的就是过滤后的4个字段 50 print(myform.cleaned_data) 51 else: 52 print(myform.cleaned_data) # 通过的部分字段,哪个字段校验通过就往这里加 53 print(myform.errors) # ErrorDict : {"校验错误的字段":["错误信息",]} 不通过的往这里加,是一个字典 54 print(myform.errors.get('email')) # ErrorList ["错误信息",] 是一个列表 55 print(myform.errors.get('email')[0]) # 取第一个错误信息,一般都是取第一个错误信息返回给前端 56 return render(request, 'multi_forms.html', locals()) 57 return render(request, 'multi_forms.html',locals()) 58 59 60 # 局部钩子与全局钩子 61 def gouzi(request): 62 # 通models,可以将forms放在一个文件,然后导入 63 from forms_app01.myforms import UserForms 64 myform = UserForms() 65 if request.method == 'POST': 66 myform = UserForms(request.POST) 67 if myform.is_valid(): 68 print(myform.cleaned_data) 69 else: 70 clean_error = myform.errors.get("__all__") 71 return render(request, 'gouzi.html', locals()) 72 return render(request, 'gouzi.html',locals())
simple_forms.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>简单forms校验</title> 6 <link rel="stylesheet" href="/static/bootstrap.min.css"> 7 </head> 8 <body> 9 <div class="container"> 10 <div class="row"> 11 <div class="col-md-6 col-md-offset-3"> 12 <h3>简单forms校验</h3> 13 <form action="" method="post"> 14 {% csrf_token %} 15 <label for="user">用户名</label> 16 <p><input type="text" name="name" id="name"></p> 17 <label for="pwd">密码</label> 18 <p><input type="password" name="pwd" id="pwd"></p> 19 <label for="r_pwd">确认密码</label> 20 <p><input type="password" name="r_pwd" id="r_pwd"></p> 21 <label for="email">邮箱</label> 22 <p><input type="text" name="email" id="email"></p> 23 <label for="phone">手机</label> 24 <p><input type="text" name="tel" id="phone"></p> 25 <input type="submit"> 26 </form> 27 </div> 28 </div> 29 </div> 30 </body> 31 </html>
multi_forms.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>渲染方式</title> 6 <link rel="stylesheet" href="/static/bootstrap.min.css"> 7 </head> 8 <body> 9 <div class="container"> 10 <div class="row"> 11 <div class="col-md-6 col-md-offset-3"> 12 <h3>渲染方式一</h3> 13 <form action="" method="post"> 14 {% csrf_token %} 15 <label for="">用户名</label> 16 {# 实例对象加字段名,django自动渲染 #} 17 {{ myform.name }} <span class="pull-right" style="color: red">{{ myform.name.errors.0 }}</span> 18 <label for="">密码</label> 19 {{ myform.pwd }}<span class="pull-right" style="color: red">{{ myform.pwd.errors.0 }}</span> 20 <label for="">确认密码</label> 21 {{ myform.r_pwd }}<span class="pull-right" style="color: red">{{ myform.r_pwd.errors.0 }}</span> 22 <label for="">邮箱</label> 23 {{ myform.email }}<span class="pull-right" style="color: red">{{ myform.email.errors.0 }}</span> 24 <label for="">手机</label> 25 {{ myform.tel }}<span class="pull-right" style="color: red">{{ myform.tel.errors.0 }}</span> 26 <input type="submit" class="btn btn-success mybtn"> 27 </form> 28 29 <hr> 30 <h3>渲染方式二</h3> 31 <form action="" method="post"> 32 {% csrf_token %} 33 {% for field in myform %} 34 <label for="">{{ field.label }}</label> 35 {{ field }} <span class="pull-right" style="color: red">{{ field.errors.0 }}</span> 36 {% endfor %} 37 <input type="submit" class="btn btn-success mybtn"> 38 </form> 39 40 <hr> 41 <h3>渲染方式三</h3> 42 <form action="" method="post"> 43 {% csrf_token %} 44 {{ myform.as_p }} 45 <input type="submit" class="btn btn-success mybtn"> 46 </form> 47 </div> 48 </div> 49 </div> 50 </body> 51 </html>
gouzi.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>钩子</title> 6 <link rel="stylesheet" href="/static/bootstrap.min.css"> 7 </head> 8 <body> 9 <div class="container"> 10 <div class="row"> 11 <div class="col-md-6 col-md-offset-3"> 12 <hr> 13 <h3>钩子</h3> 14 <form action="" method="post"> 15 {% csrf_token %} 16 {% for field in myform %} 17 <label for="">{{ field.label }}</label> 18 {{ field }} 19 <span class="pull-right" style="color: red"> 20 {% if field.label == '确认密码' %} 21 {{ clean_error.0 }} 22 {% else %} 23 {{ field.errors.0 }} 24 {% endif %} 25 </span> 26 {% endfor %} 27 <input type="submit" class="btn btn-success mybtn"> 28 </form> 29 </div> 30 </div> 31 </div> 32 </body> 33 </html>