forms组件(详细

功能:

1 校验字段功能
2 渲染标签功能
3 渲染错误信息功能
4 组件的参数配置
5 局部钩子
6 全局钩子

类中使用:

  1.定义

from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError

  2.写一个类
  3.写属性

class RegForm(forms.Form):
name=forms.CharField(max_length=8,min_length=3,label='用户名',error_messages={'max_length':'超长了'},
widget=widgets.TextInput(attrs={'class':'form-control'})

  4.局部钩子函数

def clean_name(self):
name=self.cleaned_data.get('name')
if name.startswith('sb'):
raise ValidationError('不能以sb开头')
else:
# 切记,如果正确,一定要返回name
return name

  5.全局钩子函数

def clean(self):
#一系列逻辑判断
#如果校验通过:返回cleaned_data
#如果校验不通过:raise ValidationError('两次密码不一致'),错误放到__all__
pass

views中使用:

def test(request):
if request.method=='GET':
regform=RegForm()
else:
regform=RegForm(request.POST)
if regform.is_valid():
#一般情况需要存数据库了
pass
else:
error_all=regform.errors.get('__all__')
# error_all=regform.errors['__all__']
return render(request,'register.html',locals())

模板中使用:

<form action="">

    {% for foo in regform %}
{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span>
{% endfor %}
<input type="submit"> <span>{{ error_all }}</span> </form>

最新文章

  1. css小技巧(1)
  2. apachebench的简单使用1
  3. 关于iOS10 Xcode8真机测试项目出现的问题 &quot;code signing is required for product type &#39;xxxxx&#39; in SDK &#39;iOS 10.0&quot;..
  4. 使用Bootstrap v3.3.4注意细节box-sizing
  5. Linux 在一个命令行上执行多个命令
  6. Form的用法
  7. What are Scopes?
  8. Agile.Net 组件式开发平台 - 服务器端部署
  9. cat ,more, Less区别
  10. 【转】Install MATLAB 2013a on CentOS 6.4 x64 with mode silent
  11. vector中的resize与 reserve
  12. Maven构建SSM架构,并分离层次,使用Maven 组织多项目
  13. curl 返回响应头
  14. FZU 2113(数位dp)
  15. 基于Spring Cloud和Netflix OSS 构建微服务-Part 1
  16. 刨根究底字符编码之十四——UTF-16究竟是怎么编码的
  17. Spring Boot环境下出现No operations allowed after connection close错误
  18. Spring MVC 数据绑定 (四)
  19. Duplicate entry &#39;0&#39; for key &#39;PRIMARY&#39;
  20. 软件工程(FZU2015) 学生博客列表(最终版)

热门文章

  1. [洛谷P1730] 最小密度路径
  2. bzoj 2588 : Spoj 10628. Count on a tree
  3. project 2013 删除资源
  4. 【hdu 6172】Array Challenge(数列、找规律)
  5. Apache 安装及常用参数设置
  6. 【BZOJ4316】小C的独立集(动态规划)
  7. 【BZOJ4408】[FJOI2016]神秘数(主席树)
  8. 【BZOJ5300】[CQOI2018]九连环 (高精度,FFT)
  9. 【转】C++命名空间 namespace的作用和使用解析
  10. 【转】linux清屏的几种方法