Form组件
服务端假设所有用户提交的数据都是不可信任的,所以Django框架内置了form组件来验证用户提交的信息
form组件的2大功能:
1 验证(显示错误信息)
2 保留用户上次输入的信息
3.可以生成html标签
1 验证(显示错误信息)
示例/:注册用户字段校验
模型: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())
其中视图函数中关于Widgets的详细使用,可参考:http://www.liujiangblog.com/course/django/155
2. -- 可以生成html标签
生成HTML 标签有三种渲染方式
1. 渲染成文字段落as_p()
Form.as_p()
该方法将form渲染成一系列<p>
标签,每个<p>
标签包含一个字段;
<form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-default pull-right"> </form>
2.渲染方式二循环form表单,利用字段:
rm action="" method="post"> {% 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.渲染方式三:

<form action="" method="post"> {% csrf_token %} <div> <label for="">用户名</label> {{ form.name }} </div> <div> <label for="">密码</label> {{ form.pwd }} </div> <div> <label for="">确认密码</label> {{ form.r_pwd }} </div> <div> <label for=""> 邮箱</label> {{ form.email }} </div> <input type="submit" class="btn btn-default pull-right"> </form>
3.返回并在界面表示错误
HTML示例:
<form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div> <label for="">{{ field.label }}</label> {{ field }} <span class="pull-right" style="color: red">{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" class="btn btn-default"> </form>
增加全局钩子和局部钩子的代码示例:
views:

from django.shortcuts import render,HttpResponse from django import forms # Create your views here. from django.forms import widgets from django.core.exceptions import ValidationError 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 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('两次密码不一致!') def register(request): if request.method=="POST": form=UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) # 所有干净的字段以及对应的值 else: clean_error = form.errors.get("__all__") print(form.cleaned_data) # print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]} print(form.errors.get("name")) # ErrorList ["错误信息",] return render(request, "register.html", locals()) return HttpResponse("OK") form=UserForm() return render(request,"register.html",locals())
html:

<form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div> <label for="">{{ field.label }}</label> {{ field }} <span class="pull-right" style="color: red"> {% if field.label == 'R pwd' %} <span>{{ clean_error.0 }}</span> {% endif %} {{ field.errors.0 }} </span> </div> {% endfor %} <input type="submit" class="btn btn-default"> </form>
以下几种form表单渲染方式示例,请详看:

# 通过直接form生成的HTML文件如下 # <form action="/name/" method="post"> # {% csrf_token %} # {{ form }} # <input type="submit" value="Submit" /> # </form> # 渲染后: # <form action="/name/" method="post"> # <input type="hidden" name="csrfmiddlewaretoken" value="B3iGL11TlxDRrhRhC96iDdQrJSOiUDoU8QYgw1euE2sddZONoAogOnfHJZtgSY0X"> # <label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required="" id="id_subject"> # <label for="id_message">Message:</label><textarea name="message" cols="40" rows="10" required="" id="id_message"></textarea> # <label for="id_sender">Sender:</label><input type="email" name="sender" required="" id="id_sender"> # <label for="id_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_cc_myself"> # <input type="submit" value="Submit"> # </form> # 通过直接form.as_p生成的HTML文件如下 # <form action="/name/" method="post"> # {% csrf_token %} # {{ form.as_p }} # <input type="submit" value="Submit" /> # </form> # 渲染后: # <form action="/name/" method="post"> # <input type="hidden" name="csrfmiddlewaretoken" value="bT7RLCRW7B40rLZye7rtQ9n2Nr0tvcfVIGNrwC4xq6TmdtW40yJr1jMiNyFrtxRY"> # <p><label for="id_subject">Subject:</label> <input type="text" name="subject" maxlength="100" required="" id="id_subject"></p> # <p><label for="id_message">Message:</label> <textarea name="message" cols="40" rows="10" required="" id="id_message"></textarea></p> # <p><label for="id_sender">Sender:</label> <input type="email" name="sender" required="" id="id_sender"></p> # <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p> # <input type="submit" value="Submit"> # </form> # 直接{{ form }}虽然好,啥都不用操心,但是往往并不是你想要的,比如你要使用CSS和JS,比如你要引入Bootstarps框架,这些都需要对表单内的input元素进行额外控制,那怎么办呢?手动渲染字段就可以了。 # 可以通过{{ form.name_of_field }}获取每一个字段,然后分别渲染,如下例所示: # {{ form.non_field_errors }} # <div class="fieldWrapper"> # {{ form.subject.errors }} # <label for="{{ form.subject.id_for_label }}">Email subject:</label> # {{ form.subject }} # </div> # <div class="fieldWrapper"> # {{ form.message.errors }} # <label for="{{ form.message.id_for_label }}">Your message:</label> # {{ form.message }} # </div> # <div class="fieldWrapper"> # {{ form.sender.errors }} # <label for="{{ form.sender.id_for_label }}">Your email address:</label> # {{ form.sender }} # </div> # <div class="fieldWrapper"> # {{ form.cc_myself.errors }} # <label for="{{ form.cc_myself.id_for_label }}">CC yourself?</label> # {{ form.cc_myself }} # </div> # 渲染后: # < div class ="fieldWrapper" > # < label for ="id_subject" > Email subject:</label> # < input type = "text" name = "subject" maxlength = "100" required = "" id = "id_subject" > # </div > # # < div class ="fieldWrapper" > # < labelfor ="id_message" > Your message:< / label > # < textarea name = "message" cols = "40" rows = "10" required = "" id = "id_message" > < / textarea > # </div> # # < div class ="fieldWrapper" > # < label for ="id_sender" > Your email address:< / label > # < input type = "email" name = "sender" required = "" id = "id_sender" > # </div > # # <div class ="fieldWrapper" > # <label for ="id_cc_myself" > CC yourself? < / label > # <input type = "checkbox" name = "cc_myself" id = "id_cc_myself" > # </div> # 4. 循环表单的字段: # 如果你的表单字段有相同格式的HMTL表现,那么完全可以循环生成,不必要手动的编写每个字段,减少冗余和重复代码,只需要使用模板语言中的{% for %}循环,如下所示: # {% for field in form %} # <div class="fieldWrapper"> # {{ field.errors }} # {{ field.label_tag }} {{ field }} # {% if field.help_text %} # <p class="help">{{ field.help_text|safe }}</p> # {% endif %} # </div> # {% endfor %}
{
{ field }}
中非常有用的属性,这些都是Django内置的模板语言给我们提供的方便:

属性 说明
{{ field.label }} 字段对应的label信息
{{ field.label_tag }} 自动生成字段的label标签,注意与{{ field.label }}的区别。
{{ field.id_for_label }} 自定义字段标签的id
{{ field.value }} 当前字段的值,比如一个Email字段的值someone@example.com
{{ field.html_name }} 指定字段生成的input标签中name属性的值
{{ field.help_text }} 字段的帮助信息
{{ field.errors }} 包含错误信息的元素
{{ field.is_hidden }} 用于判断当前字段是否为隐藏的字段,如果是,返回True
{{ field.field }} 返回字段的参数列表。例如{{ char_field.field.max_length }}
详细可参考:https://www.cnblogs.com/yangmingxianshen/p/8396535.html 或