django—form

form

		 1. 有input标签, 让用户可以填数据;
		 2. 校验form表单提交的数据;
		 3. 提示错误信息。

定义:

from django import forms


class regform(forms, Form):
	user = forms.CharField(label="用户名 ")
	password = form.CharField(label='密码')

使用

视图;

form-obg = regfrom()
return render(request, 'xx.html', {'form_obg'=fomr_obg})

模板:

{{ form_obg.as_p }}  # 自动生成多个p标签,包含label, input框
{{ form_obg.user }}  # 生成某个字段的inpout框
{{ form_obg.user.errors }}  # 某个字段个的错误信息
{{ form_obg.user.errors.0 }}  # 某个字段个的错误信息的第一个
{{  form_obg.errors }}  # 所有字段的错误的信息

字段与参数

label = ‘用户名’,  # 标签名字
min_length=6,  # 校验的规则,最小长度
initial=‘ xxxx’,  # 初始值
error_messages={  # 自定义错误提示
	'min_length':'太短了!',
	'required':'不能为空!',
}
widget=widgets.PasswordInput()  # 插件—指定字段的类型

校验

字段有默认的校验方法:

min_length=6
max_length=6
required=Falsse

校验的自定义规则:

validtors = [校验器1, 校验器2]

 1. form django.core.validators import RegerVaidator
RegexValidator(r'^1[3-9]\d{9}$', '号码格式不正确!')

 2. 自定义函数
 form django.core.exceptions import Validationerror

def check_name(value):
	if 'xxxx' in value:
		raise ValidationError('格式不正确')

钩子函数

  1. 局部钩子
def clean_phone(self):
	value = self.cleaned_data.get('phone')
	if re,match(r'1[3-9]\dd{9}$', value):
		return value
	
	raise ValidationError('手机号不正确')
  1. 全局钩子
def clean(self):
	pwd = self.cleaned_data.get('pwd')
	re_pwd = slef ,cleaned_data.get('re_pwd')
	 if pwd == r_pwd:
	 	return  cleaned_data
	 self.add_error('re_pwd', '两次密码不一致')
	 raise ValidationError('两次密码不一致')

猜你喜欢

转载自blog.csdn.net/qq_42221612/article/details/83149376
今日推荐