一 基本流程
1 创建form组件对应的类,比如LoginForm
2 前端的三种渲染方式:
渲染方式三种: 1 <form action="" novalidate method="post"> {% csrf_token %} {{ form_obj.as_p }} <input type="submit"> </form> 2 <form action="" novalidate method="post"> {% csrf_token %} <div> <label for="">用户名</label> {{ form_obj.user }} <span>{{ form_obj.errors.user.0 }}</span> </div> <div> <label for="">密码</label> {{ form_obj.pwd }}<span>{{ form_obj.errors.pwd.0 }}</span> </div> <input type="submit"> </form> 3 <form action="" novalidate method="post"> {% csrf_token %} {% for field in form_obj %} <div> <label for="">{{ field.label }}</label> {{ field }} </div> {% endfor %} <input type="submit"> </form>
二 注册校验
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.forms import widgets
1 class RegForm(forms.Form): 2 user = forms.CharField(max_length=18, min_length=3, 3 error_messages={ 4 ‘required‘: ‘不能为空‘, 5 ‘min_length‘: ‘too short‘, 6 ‘max_length‘: "too long" 7 }) 8 pwd = forms.CharField(max_length=32, min_length=3, 9 error_messages={ 10 ‘max_length‘: "too long", 11 ‘required‘: ‘不能为空‘, 12 ‘min_length‘: ‘too short‘, 13 }, 14 widget=widgets.PasswordInput(attrs={})) 15 repeat_pwd = forms.CharField(label=‘确认密码‘, 16 max_length=32, 17 error_messages={}, 18 widget=widgets.PasswordInput(attrs={})) 19 email = forms.EmailField( 20 error_messages={ 21 "invalid": ‘格式错误‘ 22 } 23 ) 24 25 tel = forms.CharField() 26 27 def clean_user(self): 28 val = self.cleaned_data.get("user") 29 ret = Userinfo.objects.filter(name=val) 30 if not ret: 31 return val 32 else: 33 raise ValidationError("该用户已经注册") 34 35 def clean_tel(self): 36 val = self.cleaned_data.get(‘tel‘) 37 import re 38 ret = re.search("1[356789]\d{9}$", val) 39 if ret: 40 return val 41 else: 42 raise ValidationError("手机号格式错误") 43 44 def clean(self): 45 pwd = self.cleaned_data.get(‘pwd‘) 46 repeat_pwd = self.cleaned_data.get(‘repeat_pwd‘) 47 if pwd == repeat_pwd: 48 return self.cleaned_data 49 else: 50 raise ValidationError("两次密码不一致")
1 def reg(request): 2 if request.method == ‘POST‘: 3 reg_form = RegForm(request.POST) 4 if reg_form.is_valid(): 5 print(reg_form.cleaned_data) # dict 6 name = reg_form.cleaned_data.get("user") 7 pwd = reg_form.cleaned_data.get("pwd") 8 Userinfo.objects.create(name=name, pwd=pwd) 9 10 return redirect(‘/login/‘) # 注册成功去登录 11 else: 12 all_error = reg_form.errors.get("__all__") 13 return render(request, ‘reg.html‘, locals()) 14 15 reg_form = RegForm() 16 return render(request, ‘reg.html‘, {‘reg_form‘: reg_form})
1 <body> 2 <h3>注册页面</h3> 3 <form action="" novalidate method="post"> 4 {% csrf_token %} 5 {% for field in reg_form %} 6 <div> 7 <label for="">{{ field.label }}</label> 8 {{ field }}<span>{{ field.errors.0 }}</span> 9 {% if field.label == ‘确认密码‘ %} 10 <span>{{ all_error.0 }}</span> 11 {% endif %} 12 </div> 13 {% endfor %} 14 <input type="submit"> 15 </form> 16 </body>