基于ModelForm实现注册并检验注册信息
一、在app下创建form.py
代码里参照的表为Django自带的auth_user表
1 from django import forms 2 import re 3 from django.contrib.auth.models import User 4 from django.core.exceptions import ValidationError 5 from django.forms import widgets as wid 6 class UserModelForm(forms.ModelForm): 7 class Meta: 8 #参照表 9 model=User 10 #显示表里的所有字段 11 fields='__all__' 12 #选取表里显示的字段 13 fields=['username','password','email'] 14 #排除不显示的字段 15 exclude=['title'] 16 labels={ 17 'username':'用户名', 18 'password':'密码', 19 'email':'邮箱' 20 } 21 #设置提示信息 22 error_messages={ 23 'username':{'required':'用户名不能为空'}, 24 'password':{'required':'密码不能为空'}, 25 'email':{'required':'邮箱不能为空'}, 26 'rpassword':{'required':'确认密码不能为空'} 27 } 28 widgets={ 29 'pub_data':wid.TextIput(attrs={'type':'data'}) 30 } 31 #可以设置表里没有的字段 32 rpassword = forms.CharField(min_length=5, 33 label='确认密码', 34 error_messages={'required':'确认密码不能为空'} 35 ) 36 def clean_username(self): 37 val = self.cleaned_data.get('username') 38 ret = User.objects.filter(username=val).first() 39 if ret: 40 raise ValidationError('用户名已存在') 41 else: 42 return val 43 44 def clean_email(self): 45 val = self.cleaned_data.get('email') 46 if re.search('\w+@136.com$', val): 47 return val 48 else: 49 raise ValidationError('邮箱必须是136格式') 50 def clean(self): 51 password=self.cleaned_data.get('password') 52 rpassword=self.cleaned_data.get('rpassword') 53 if password and rpassword: 54 if password == rpassword: 55 return self.cleaned_data 56 else: 57 raise ValidationError('两次密码不一致') 58 else: 59 return self.cleaned_data 60 def __init__(self,*args,**kwargs): 61 super().__init__(*args,**kwargs) 62 for filed in self.fields.values(): 63 #可以设置统一的属性 64 # filed.error_messages={'required':'该用户信息不能为空'} 65 filed.widget.attrs.update({"class":'form-control'})
二、views 视图函数
def regist(request): res={'error':'','user':None} if request.method=="GET": form=UserModelForm() return render(request,'regist.html',{'form':form}) else: form=UserModelForm(request.POST) if form.is_valid(): obj=form.save() #create 保存信息 res['user']='ok' else: error=form.errors res['error']=error return JsonResponse(res)
三、HTML页面 表单通过form类渲染
使用Ajax发送数据,根据返回信息将错误提示显示到对应的表单下
1 <body> 2 <div class="container"> 3 <div class="row c1"> 4 <div class="col-md-8 col-md-offset-2"> 5 {% csrf_token %} 6 <form action="" method="post" novalidate> 7 {% for field in form %} 8 <div> 9 <label for="">{{ field.label }}</label> 10 {{ field }} <span class="error"></span> 11 {% endfor %} 12 </div> 13 <input type="button" class="btn btn-warning" value="注册"> 14 </form> 15 </div> 16 </div> 17 </div> 18 19 <script> 20 $(function () { 21 $('.btn').click(function () { 22 $.ajax({ 23 url:'', 24 type:'post', 25 data:{ 26 username:$('#id_username').val(), 27 password:$('#id_password').val(), 28 rpassword:$('#id_rpassword').val(), 29 email:$('#id_email').val(), 30 csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val() 31 }, 32 success:function (res) { 33 if(res.user){ 34 location.href='/login/' 35 } 36 else{ 37 //清除错误 38 $('.error').html(''); 39 $('.form-control').removeClass('has-error'); 40 41 //显示新错误 42 $.each(res.error,function (i,j) { 43 if(i=='__all__'){ 44 $('#id_rpassword').next().html(j[0]) 45 } 46 $('#id_'+i).next().html(j[0]).css('color','red').parent().addClass('has-error') 47 }); 48 } 49 50 console.log(res) 51 } 52 }) 53 }) 54 }) 55 </script> 56 </body>