标签:print htm val rac ensure 通过 return username spl
# 第一步需要一个form类 from django import forms class MyForm(forms.Form): name = forms.CharField(max_length=6) password = forms.CharField(max_length=8,min_length=3) email = forms.EmailField(required=True) #第二步实例化form对象 form_obj = MyForm({‘name‘:‘jason‘}) # 第三步查看数据校验是否合法 form_obj.is_valid() # 只有当所有的字段都校验通过才会返回True # 第四步查看校验错误的信息 form_obj.errors # 这个里面放的是所有校验未通过的字段及错误提示 {‘name‘: [‘Ensure this value has at most 6 characters (it has 7).‘], ‘password‘: [‘Ensure this value has at least 3 characters (it has 2).‘],
‘email‘: [‘Enter a valid email address.‘]} # 第五步查看校验通过的数据 form_obj.cleaned_data # 符合校验规则数据都会被放到该对象中 # form组件校验数据的规则从上往下依次取值校验 校验通过的放到cleaned_data 校验失败的放到errors # 注意: form中所有的字段默认都是必须传值的(required=True) 校验数据的时候可以都传(多传的数据不会做任何的校验,不会影响form校验规则)
from django import forms class MyForm(forms.Form): username = forms.CharField(max_length=6, label=‘用户名‘) password = forms.CharField(max_length=8, min_length=3) email = forms.EmailField() def reg(request): # 生成一个空对象 form_obj = MyForm() return render(request, ‘reg.html‘, locals())
reg.html:
<h1>第一种渲染标签的方式</h1> {{ form_obj.as_p }} {{ form_obj.as_ul }} <h1>第二种渲染标签的方式</h1> <form action=""> <p>{{ form_obj.username.label }}{{ form_obj.username }}</p> <p>{{ form_obj.password.label }}{{ form_obj.password }}</p> <p>{{ form_obj.email.label }}{{ form_obj.email }}</p> <input type="submit"> </form> <h1>第三种渲染标签的方式</h1> <form action="" method="post"> {% for foo in form_obj %} <p>{{ foo.label }}{{ foo }}</p> {% endfor %} <input type="submit"> </form>
from django import forms class MyForm(forms.Form): username = forms.CharField(max_length=6, label=‘用户名‘, error_messages={ ‘max_length‘: ‘用户名最长为6位‘, ‘required‘: ‘用户名不能为空‘ }) password = forms.CharField(max_length=8, min_length=3, error_messages={ ‘max_length‘: ‘密码最长为8位‘, ‘required‘: ‘密码不能为空‘, ‘min_length‘: ‘密码最少3位‘ }) email = forms.EmailField(error_messages={ ‘required‘: ‘邮箱不能为空‘, ‘invalid‘: ‘邮箱格式不正确‘ }) def reg(request): # 生成一个空对象 form_obj = MyForm() if request.method == ‘POST‘: print(request.POST) form_obj = MyForm(request.POST) if form_obj.is_valid(): print(form_obj.cleaned_data) models.User.objects.create(**form_obj.cleaned_data) return render(request, ‘reg.html‘, locals())
reg.html:
<h1>第三种渲染标签的方式</h1> <form action="" method="post" novalidate> {% for foo in form_obj %} <p> {{ foo.label }}{{ foo }} <span>{{ foo.errors.0 }}</span> </p> {% endfor %} <input type="submit"> </form>
标签:print htm val rac ensure 通过 return username spl
原文地址:https://www.cnblogs.com/zhangguosheng1121/p/11041925.html