Django组件—forms组件
Posted stfei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django组件—forms组件相关的知识,希望对你有一定的参考价值。
forms组件:
校验字段功能:
针对一个实例:注册用户。
模型:models.py
class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) email=models.EmailField() 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"> {% csrf_token %} <div> <label for="user">用户名</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> <input type="submit"> </form> </body> </html>
视图函数:register
# forms组件 from django.forms import widgets wid_01=widgets.TextInput(attrs={"class":"form-control"}) wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) class UserForm(forms.Form): 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) # 所有干净的字段以及对应的值 else: print(form.cleaned_data) # print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]} print(form.errors.get("name")) # ErrorList ["错误信息",] return HttpResponse("OK") form=UserForm() return render(request,"register.html",locals())
渲染标签功能:
渲染方式1:
<h3>渲染方式一</h3> <form action="" method="post" novalidate> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> </body> </html>
直接将form对象传入,然后通过.as_p方法可以将每一个字段都以input标签建成。
input标签前的名字,默认是字段名,若想显示为中文,则需要在字段属性中,添加lable.如:
class UserForm(forms.Form): name = forms.CharField(min_length=4,label="姓名") pwd = forms.CharField(max_length=16,label="密码") age = forms.IntegerField(label="年龄") tel = forms.CharField(label="电话")
渲染方式2:
<h3>渲染方式二</h3> <form action="" method="post" novalidate> {% csrf_token %} <div> <label for="">用户名</label> {{ form.name }} {# 一定要是form.字段名#} </div> <div> <label for="">密码</label> {{ form.pwd }} </div> <div> <label for="">年龄</label> {{ form.age }} </div> <div> <label for="">电话</label> {{ form.tel }} </div> <input type="submit"> </form>
渲染方式三:form表单外是加了一些bootstrap样式
<div class="container"> <div class="row"> <div class="col-md-8"> <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="">{{ field.label }}</label> {{ field }} </div> {% endfor %} <input type="submit"> </form> </div> </div> </div>
显示错误与重置输入信息功能:
视图:
from django.shortcuts import render,HttpResponse,reverse,redirect # Create your views here. from app01.form import UserForm def register(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): print("######success#######") print(form.cleaned_data) print(form.errors) print(type(form.errors)) return HttpResponse("添加成功") else: print("##########failed##########") print(form.cleaned_data) # 正确的情况下会显示的字典。 print(form.errors) # 是一个字典。 print(form.errors.get("name")) # 拿到的是ul里面包着错误信息 print(form.errors.get("name")[0]) # 拿到的是错误信息 return render(request,"register.html",locals()) form = UserForm() return render(request,"register.html",locals())
模板:
<div class="container"> <div class="row"> <div class="col-md-8 col-lg-offset-2"> <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="">{{ field.label }}</label> {{ field }} <span class="errors pull-left">{{ field.errors.0 }}</span> </div> {% endfor %} <div class="form-group"> <input type="submit" class=" btn btn-success btn-sm"> </div> </form> </div> </div> </div>
局部钩子与全局钩子:
模板:
from django import forms from django.core.exceptions import ValidationError,NON_FIELD_ERRORS from django.forms import widgets # widgets可以设置css样式 class UserForm(forms.Form): name = forms.CharField(min_length=4,label="姓名",widget=widgets.TextInput(attrs=({"class":"form-control"}))) pwd = forms.CharField(max_length=16,label="密码",widget=widgets.PasswordInput(attrs=({"class":"form-control"}))) age = forms.IntegerField(label="年龄",widget=widgets.TextInput(attrs=({"class":"form-control"}))) tel = forms.CharField(label="电话",widget=widgets.TextInput(attrs=({"class":"form-control"}))) def clean_name(self): # 函数名格式必须是 clean_字段名。源码规定。 val = self.cleaned_data.get("name") # 从正确字典中获取name数据。 if not val.isdigit(): # 如果不是纯数字。 return val # 返回源数据。 else: raise ValidationError(‘用户名不能是纯数字‘) # 否则就抛出错误。 def clean_pwd(self): val = self.cleaned_data.get("pwd") if len(val)>6: return val else: raise ValidationError("密码不足6位") def clean_age(self): val = self.cleaned_data.get("age") if int(val)>=18: return val else: raise ValidationError(‘未成年不得入内‘) def clean_tel(self): val = self.cleaned_data.get("tel") if int(val)==11: return val else: raise ValidationError("手机号不合法")
视图:
<div class="container"> <div class="row"> <div class="col-md-8 col-lg-offset-2"> <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="">{{ field.label }}</label> {{ field }} <span class="errors pull-left">{{ field.errors.0 }}</span> </div> {% endfor %} <div class="form-group"> <input type="submit" class=" btn btn-success btn-sm"> </div> </form> </div> </div> </div>
以上是关于Django组件—forms组件的主要内容,如果未能解决你的问题,请参考以下文章