forms组件
一、app01.models.py
1
2
3
4
5
6
7
8
9
10
|
from django.db import models class UserInfo(models.Model): nid = models.BigAutoField(primary_key = True ) name = models.CharField(verbose_name = ‘用户名‘ , max_length = 32 , unique = True ) pwd = models.CharField(verbose_name = ‘密码‘ , max_length = 64 ) email = models.EmailField(verbose_name = ‘邮箱‘ , unique = True ) tel = models.CharField(verbose_name = ‘手机‘ ) avatar = models.ImageField(verbose_name = ‘头像‘ ) create_time = models.DateTimeField(verbose_name = ‘创建时间‘ , auto_now_add = True ) |
二、app01.myforms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
from django import forms from django.forms import widgets from app01.models import UserInfo from django.core.exceptions import ValidationError class RegisterForm(forms.Form): name = forms.CharField( min_length = 6 , max_length = 32 , label = "用户名" , error_messages = { "required" : "用户名不能为空" , "min_length" : "用户名长度不能小于6个字符" , "max_length" : "用户名长度不能大于32个字符" }, widget = widgets.TextInput(attrs = { "class" : "form-control" }) ) pwd = forms.CharField( min_length = 6 , max_length = 32 , label = "密码" , error_messages = { ‘required‘ : ‘密码不能为空.‘ }, widget = widgets.PasswordInput(attrs = { "class" : "form-control" }) ) r_pwd = forms.CharField( min_length = 6 , max_length = 32 , label = "确认密码" , error_messages = { "required" : "密码不能为空" }, widget = widgets.TextInput(attrs = { "class" : "form-control" }) ) email = forms.EmailField( label = "邮箱" , error_messages = { "required" : "邮箱不能为空" , "invalid" : "格式错误" }, widget = widgets.TextInput(attrs = { "class" : "form-control" }) ) tel = forms.CharField( label = "手机号" , widget = widgets.TextInput(attrs = { "class" : "form-control" }) ) # 局部钩子 def clean_name( self ): val = self .cleaned_data.get( "name" ) ret = UserInfo.objects. filter (name = val) if not ret: return val else : raise ValidationError( "该用户已注册!" ) def clean_email( self ): val = self .cleaned_data.get( "email" ) ret = UserInfo.objects. filter (email = val) if not ret: return val else : raise ValidationError( "该邮箱已注册!" ) def clean_tel( self ): val = self .cleaned_data.get( "tel" ) if len (val) = = 11 : return val else : raise ValidationError( "手机号格式错误" ) # 全局钩子 def clean( self ): pwd = self .cleaned_data.get( ‘pwd‘ ) r_pwd = self .cleaned_data.get( ‘r_pwd‘ ) if pwd and r_pwd: if pwd = = r_pwd: return self .cleaned_data else : # raise ValidationError(‘两次密码不一致‘) # 加在全局的错误里面 form.errors.get("__all__") self .add_error( "r_pwd" , ValidationError( ‘两次密码不一致‘ )) #加在r_pwd的错误里 else : return self .cleaned_data |
三、app01.views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
from django.shortcuts import render,HttpResponse from app01.myforms import * def reg(request): if request.method = = "POST" : form = RegisterForm(request.POST) # form表单的name属性值应该与forms组件字段名称一致 if form.is_valid(): # 验证成功做什么 form.cleaned_data.pop( ‘r_pwd‘ ) user_info = form.cleaned_data UserInfo.objects.create( * * user_info) request.session[ ‘user_info‘ ] = user_info return redirect( ‘/‘ ) else : return render(request, "reg.html" , locals ()) form = RegisterForm() return render(request, "reg.html" , locals ()) ‘‘‘ form=UserForm({"name":"bubu","email":"123@qq.com","xxxx":"123123123"}) :xxxx字段不会验证,只验证UserForm类里面有的字段 form.is_valid() :返回布尔值 form.cleaned_data :所有干净的字段以及对应的值{"name":"bubu","email":"123@qq.com"} form.errors :ErrorDict : {"校验错误的字段":["错误信息",]} form.errors.get("name") :ErrorList ["错误信息",] form.errors.get("name")[0] :取出第一个错误信息 全局钩子错误 forms中: raise ValidationError(‘两次密码不一致‘) #加在全局的错误里面 form.errors.get("__all__") self.add_error("r_pwd", ValidationError(‘两次密码不一致‘)) views.py中:errors=form.errors.get("__all__") 模板中:<span>{{ errors.0 }}</span> ‘‘‘ |
四、templates.reg.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
<! DOCTYPE html> < html lang="en"> < head > < meta charset="UTF-8"> < title >Title</ title > < style > .error{ color: red; } .register { width: 400px; margin-top: 20px; margin-left: auto; margin-right: auto; border: 1px solid #f0f0f0; padding: 10px 30px 50px 30px; -webkit-box-shadow: 5px 10px 10px rgba(0, 0, 0, .05); box-shadow: 5px 10px 10px rgba(0, 0, 0, .05); } .register h3{font-size: 25px; text-align: center;font-weight: bold;} </ style > <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> < link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </ head > < body > < div class="register"> < h3 >用户注册</ h3 > < form action="" method="post" novalidate> {% csrf_token %} < div class="form-group"> < label for="">{{ form.name.label }}</ label > {{ form.name }} < span class="pull-right error">{{ form.name.errors.0 }}</ span > </ div > < div class="form-group"> < label for="">{{ form.pwd.label }}</ label > {{ form.pwd }} < span class="pull-right error">{{ form.pwd.errors.0 }}</ span > </ div > < div class="form-group"> < label for="">确认密码</ label > {{ form.r_pwd }} < span class="pull-right error">{{ form.r_pwd.errors.0 }}</ span >< span class="pull-right error">{{ errors.0 }}</ span > </ div > < div class="form-group"> < label for="">邮箱</ label > {{ form.email }} < span class="pull-right error">{{ form.email.errors.0 }}</ span ></ div > < div class="form-group"> < label for="">手机号</ label > {{ form.tel }} < span class="pull-right error">{{ form.tel.errors.0 }}</ span ></ div > < input type="submit" class="btn btn-default" value="注册"/> </ form > <!-- <h3>forms组件渲染方式2</h3> <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="">{{ field.label }}</label> {{ field }} <span class="pull-right error">{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" class="btn btn-default" value="注册"/> </form> <h3>forms组件渲染方式3</h3> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-default" value="注册"/> </form> --> </ div > </ body > </ html > |