django重写form表单中的局部钩子函数
from django import forms
from django.core.exceptions import ValidationError
from jax import models class RegForm(forms.Form):
username = forms.CharField(
max_length=16,
label="用户名",
error_messages={
"max_length": "用户名最长16位",
"required": "用户名不能为空!",
},
widget=forms.TextInput(
attrs={"class":"form-control", "placeholder": "用户名"},
)
) password = forms.CharField(
min_length=6,
label="密码",
error_messages={
"required": "密码不能为空",
"min_length": "密码不能少于6位",
},
widget = forms.PasswordInput(
attrs={"class": "form-control", "placeholder": "密码"},
)
) re_password = forms.CharField(
min_length=6,
label="确认密码",
error_messages={
"required": "密码不能为空",
"min_length": "密码不能少于6位",
},
widget=forms.PasswordInput(
attrs={"class": "form-control", "placeholder": "密码"},
)
) email = forms.EmailField(
label="邮箱",
error_messages={
"invalid": "请输入正确的邮箱格式",
"required": "邮箱不能为空",
},
widget=forms.EmailInput(
attrs={"class": "form-control", "placeholder": "邮箱"},
)
) # 重写全局的钩子函数,对确认密码做校验
def clean(self):
password = self.cleaned_data.get("password")
re_password = self.cleaned_data.get("re_password") if re_password and re_password != password:
self.add_error("re_password", ValidationError("两次密码不一致")) else:
return self.cleaned_data # 重写username局部钩子
def clean_username(self):
username = self.cleaned_data.get("username")
is_exist = models.UserInfo.objects.filter(username=username)
if is_exist:
self.add_error("username", ValidationError("该用户已经存在!"))
else:
return username # 重写email局部钩子
def clean_email(self):
email = self.cleaned_data.get("email")
is_exist = models.UserInfo.objects.filter(email=email)
if is_exist:
self.add_error("email", ValidationError("该邮箱已经注册!"))
else:
return email
django的form表单中定义的字段,都有对应的id以及方法,例如id_username、clean_username,这里的方法均为django中forms.Form源码类BaseForm定义
例:
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=None,
empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None):
self.is_bound = data is not None or files is not None
self.data = {} if data is None else data
self.files = {} if files is None else files
self.auto_id = auto_id
if prefix is not None:
self.prefix = prefix
self.initial = initial or {}
self.error_class = error_class
# Translators: This is the default suffix added to form field labels
self.label_suffix = label_suffix if label_suffix is not None else _(':')
self.empty_permitted = empty_permitted
self._errors = None # Stores the errors after clean() has been called. # The base_fields class attribute is the *class-wide* definition of
# fields. Because a particular *instance* of the class might want to
# alter self.fields, we create self.fields here by copying base_fields.
# Instances should always modify self.fields; they should not modify
# self.base_fields.
self.fields = copy.deepcopy(self.base_fields)
self._bound_fields_cache = {}
self.order_fields(self.field_order if field_order is None else field_order)
def _clean_fields(self):
for name, field in self.fields.items():
# value_from_datadict() gets the data from the data dictionaries.
# Each widget type knows how to retrieve its own data, because some
# widgets split data over several HTML fields.
if field.disabled:
value = self.get_initial_for_field(field, name)
else:
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
try:
if isinstance(field, FileField):
initial = self.get_initial_for_field(field, name)
value = field.clean(value, initial)
else:
value = field.clean(value)
self.cleaned_data[name] = value
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
except ValidationError as e:
self.add_error(name, e)
def clean(self):
"""
Hook for doing any extra form-wide cleaning after Field.clean() has been
called on every field. Any ValidationError raised by this method will
not be associated with a particular field; it will have a special-case
association with the field named '__all__'.
"""
return self.cleaned_data def has_changed(self):
"""Return True if data differs from initial."""
return bool(self.changed_data)
django重写form表单中的局部钩子函数的更多相关文章
- django基础之day09,创建一个forms表单组件进行表单校验,知识点:error_messages,label,required,invalid,局部钩子函数,全局钩子函数, forms_obj.cleaned_data,forms_obj.errors,locals(), {{ forms.label }}:{{ forms }},{{ forms.errors.0 }}
利用forms表单组件进行表单校验,完成用户名,密码,确认密码,邮箱功能的校验 该作业包含了下面的知识点: error_messages,label,required,invalid,局部钩子函数,全 ...
- Django之form表单组件
Form介绍 我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来. 与此同时我们在好多场景下都需要对用户的输入做校验,比如校验用户是否 ...
- Django的Form表单验证
Form(from django import forms) 简短理解:后端提供了一个类:from django import forms,继承此类定义子类.子类中定义和form表单中提交到name名 ...
- django - 总结 - form表单
{{ form.as_table }} 以表格的形式将它们渲染在<tr> 标签中 {{ form.as_p }} 将它们渲染在<p> 标签中 {{ form.as_ul }} ...
- Django 之 form表单
Django中的Form表单 1.背景 平时我们在书写form表单时,经常都是手动的去写一些input标签,让用户输入一些功能,进行一些校验的判断,等等.Django中的form表单就能够帮我们去实现 ...
- 转载:Django之form表单
转载: 一.使用form类创建一个表单 先定义好一个RegForm类: forms.py from django import forms # 导入forms类 class NameForm(form ...
- Django之form表单详解
构建一个表单 假设你想在你的网站上创建一个简单的表单,以获得用户的名字.你需要类似这样的模板: <form action="/your-name/" method=" ...
- web框架-(六)Django补充---form表单验证
一.form表单验证 1. 常规html页面的form表单验证 常规页面中,如果想实现对表单中用户输入信息的数据验证,需要配合Ajax来实现. 使用前我们先来熟悉下函数参数:request,其中包含的 ...
- Django--分页器(paginator)、Django的用户认证、Django的FORM表单
分页器(paginator) >>> from django.core.paginator import Paginator >>> objects = ['joh ...
随机推荐
- EF CodeFirst简单实例
运行环境:VS2012,添加的EntityFramework为6.0.2 版本不用太关心,只要知道原理就行了: 基本代码就这几行: namespace ConsoleApplication1 { ...
- 如何提高web页面的性能
1.浏览器渲染原理解析 想要提高网页的性能,首要的便是要理解浏览器渲染原理,下面关于浏览器的原理解析,我们以chrome内核webkit为例,其他内核的浏览器原理也基本大同小异,可触类旁通. 如上图所 ...
- android-tip-关于SpannableString的使用
如果想单独设置TextView上其中几个字的样式,该怎么办? 答案是使用SpannableString. 使用SpannableString可以为TextView上的某字或某些字设置: 前景色(For ...
- [转]NDK编译库运行时报dlopen failed: cannot locate symbol "__exidx_end" 解决办法
原文链接:http://blog.csdn.net/acm2008/article/details/41040015 当用NDK编译的库在运行加载时报如下错: dlopen("/data/d ...
- eclipse 环境安装
eclipse 安装SVN http://blog.csdn.net/rilaohn/article/details/70312827 eclipse server 不见了 http://www.jb ...
- Linux buffer and cache
A buffer is something that has yet to be "written" to disk. A cache is something that has ...
- 633E Binary Table
传送门 分析 我们发现n特别小,所以可以从这里入手 我们记录出所有列中某一种状态的列有多少个 我们再记录出每种列最少有多少个1(原来的1的个数和取反后的个数去最小值) 于是我们可以得出对于所有列异或一 ...
- Python正则表达式的七个使用范例-乾颐堂
作为一个概念而言,正则表达式对于Python来说并不是独有的.但是,Python中的正则表达式在实际使用过程中还是有一些细小的差别. 本文是一系列关于Python正则表达式文章的其中一部分.在这个系列 ...
- hdu Lovekey(水题)
#include<stdio.h> #include<string.h> ]; int main() { ],s2[]; int l1,l2,i,j,k; while(scan ...
- 浅谈css float
相信许多许多Web前端的朋友一定被float这个属性给困扰过吧,有时候用它来布局很方便,能够实现元素快速的水平排列,但有时候它又像一个精灵,让人无法琢磨透它方位.在网上也看了一些关于float的帖子, ...