一、forms组件
利用下面一个注册新用户的示例,来学习forms表单组件的功能。
1、校验字段功能
模型:models.py
class UserInfo(models.Model): name = models.CharField(max_length=32) pwd = models.CharField(max_length=32) email = models. CharField(max_length=32) tel = models.CharField(max_length=32)
模板:register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post" novalidate> {% csrf_token %} <div> <label for="name">用户名</label> <p><input type="text" name="name" id="name"></p> </div> <div> <label for="pwd">密码</label> <p><input type="password" name="pwd" id="pwd"></p> </div> <div> <label for="r_pwd">确认密码</label> <p><input type="password" name="r_pwd" id="r_pwd"></p> </div> <div> <label for="email">邮箱</label> <p><input type="text" name="email" id="email"></p> </div> <div> <label for="tel">手机号</label> <p><input type="text" name="tel" id="tel"></p> </div> <input type="submit"> </form> </body> </html>
视图函数:view.py
from django.shortcuts import render,HttpResponse from django import forms from django.forms import widgets from app01.models import UserInfo wid_01=widgets.TextInput(attrs={"class":"form-control"}) wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) class UserForm(forms.Form): # 定义一个forms组件类 name=forms.CharField(max_length=32, widget=wid_01) pwd=forms.CharField(max_length=32,widget=wid_02) r_pwd=forms.CharField(max_length=32,widget=wid_02) email=forms.EmailField(widget=wid_01) tel=forms.CharField(max_length=32,widget=wid_01) def register(request): if request.method=="POST": form=UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) # 所有干净的字段以及对应的值 UserInfo.objects.create(**form.cleaned_data) else: print(form.cleaned_data) # {"字段1":"值1","字段2":"值2"} print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]} print(form.errors.get("name")) # ErrorList ["错误信息",] return render(request,"register.html",locals()) form=UserForm() return render(request,"register.html",locals())
2、渲染标签功能
方式一(不常用,不够灵活):
<form action="" method="post" novalidate > {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-default pull-right"> </form>
方式二:
<form action="" method="post" novalidate > {% csrf_token %} <div> <label for="id_name">用户名</label> {{ form.name }} </div> <div> <label for="id_pwd">密码</label> {{ form.pwd }} </div> <div> <label for="id_r_pwd">确认密码</label> {{ form.r_pwd }} </div> <div> <label for="id_email"> 邮箱</label> {{ form.email }} </div> <div> <label for="id_tel"> 手机号</label> {{ form.tel }} </div> <input type="submit" class="btn btn-default pull-right"> </form>
方式三(for循环遍历,常用):
<form action="" method="post" novalidate > {% csrf_token %} {% for field in form %} <div> <label for="">{{ field.label }}</label> {{ field }} </div> {% endfor %} <input type="submit" class="btn btn-default pull-right"> </form>
3、显示错误与重置输入信息功能
模板:register.html
<form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div> <label for="">{{ field.label }}</label> {{ field }} <span style="color: red">{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" class="btn btn-default"> </form>
4、局部钩子与全局钩子
视图:views.py
from django.shortcuts import render,HttpResponse from django import forms from django.forms import widgets from app01.models import UserInfo wid_01=widgets.TextInput(attrs={"class":"form-control"}) wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) class UserForm(forms.Form): # 定义一个forms组件类 name=forms.CharField(max_length=32, widget=wid_01) pwd=forms.CharField(max_length=32,widget=wid_02) r_pwd=forms.CharField(max_length=32,widget=wid_02) email=forms.EmailField(widget=wid_01) tel=forms.CharField(max_length=32,widget=wid_01) # 局部钩子 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 and r_pwd: if pwd==r_pwd: return self.cleaned_data else: raise ValidationError('两次密码不一致!') else: return self.cleaned_data
def register(request): if request.method=="POST": form=UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) # 所有干净的字段以及对应的值 UserInfo.objects.create(**form.cleaned_data) else: print(form.cleaned_data) # {"字段1":"值1","字段2":"值2"} print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]} print(form.errors.get("name")) # ErrorList ["错误信息",] clean_error=form.errors.get("__all__") return render(request,"register.html",locals()) form=UserForm() return render(request,"register.html",locals())