标签:from class char rect 错误 for put action integer
1 ‘‘‘
2 Form组件
3 - 对用户请求的验证
4 - form
5 - Ajax
6 - 生成HTML代码
7
8 a. 创建一个类
9 b. 类中创建对应字段(包括正则表达式)
10 c. GET
11 - obj = Fr() 生成HTML代码
12 d. POST
13 - obj = Fr(request.POST)
14 - if obj.is_valid(): # 判断是否验证成功
15 obj.cleaned_data
16 else:
17 obj.errors
18 ‘‘‘
1 # 创建类,对应字段
2 from django import forms
3 from django.forms import fields
4 class F1Form(forms.Form):
5 user = fields.CharField(required=True,
6 min_length=6,
7 max_length=32,
8 error_messages={
9 ‘required‘: ‘用户名不能为空‘,
10 ‘min-length‘: ‘太短‘,
11 ‘invalid‘: ‘格式错误‘ # 格式错误都用invalid
12 }
13 )
14 pwd = fields.CharField(required=True,
15 min_length=20,
16 error_messages={
17 ‘required‘: ‘密码不能为空‘
18 }
19 )
20 age = fields.IntegerField(required=True)
21 email = fields.EmailField(required=True)
1 def f1(request):
2 if request.method == "GET":
3 # 生成HTML
4 obj = F1Form()
5 return render(request,‘f1.html‘,{‘obj‘:obj})
6 else:
7 # u = request.POST.get("user") # 非空,长度6到32
8 # p = request.POST.get("pwd") # 非空,大于32
9 # a = request.POST.get("age") # 非空,整数
10 # e = request.POST.get("email") # 非空,邮箱格式
11 # print(u,p,a,e)
12 obj = F1Form(request.POST)
13 # obj.is_valid()是否全部验证成功
14 if obj.is_valid():
15 # 用户提交的数据
16 print(obj.cleaned_data)
17 return redirect(‘http://www.xiaohuar.com‘)
18 else:
19 # 验证错误信息
20 print(obj.errors)
21 return render(request, ‘f1.html‘, {‘obj‘: obj})
1 <form action="/f1.html" method="POST">
2 <p>{{obj.user}}{{obj.errors.user.0}}</p>
3 <p>{{obj.pwd}}{{obj.errors.pwd.0}}</p>
4 <p>{{obj.age}}{{obj.errors.age.0}}</p>
5 <p>{{obj.email}}{{obj.errors.email.0}}</p>
6 <p><input type="submit" value="提交"></p>
7 </form>
西游之路——python全栈——Django的form组件初识
标签:from class char rect 错误 for put action integer
原文地址:https://www.cnblogs.com/Lujun1028/p/9605463.html