django预留的钩子方法:
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) |
自定义钩子方法:
针对一个字段做验证的时候使用clean_%s自定义验证 def clean_username(self): username = self.cleaned_data.get("username") username_exist = models.UserInfo.objects.filter(username=username) if username_exist: self.add_error("username",ValidationError("用户名已存在")) def clean_phone(self): phone = self.cleaned_data.get('phone') phone_exist = models.UserInfo.objects.filter(phone=phone) if phone_exist: self.add_error('phone', ValidationError("手机号码已存在")) 针对多个字段做验证的时候使用clean自定义验证 def clean(self): pwd1 = self.cleaned_data.get('password') pwd2 = self.cleaned_data.get('re_password') if pwd1 == pwd2: pass else: self.add_error('re_password', ValidationError('密码输入不一致')) |
jquery绑定数据:
jquery使用on(input,func)绑定事件input框有输出就可以检测。