from django.shortcuts import render,HttpResponse from django import forms from django.core.exceptions import ValidationError #校验错误 class UserInfo(forms.Form): username = forms.CharField( label=‘用户名‘, required=True, ) password = forms.CharField( label=‘密码‘, widget=forms.widgets.PasswordInput(render_value=True) ) def clean_username(self): #此处自定义一个校验规则的函数:用户名不能含有admin value = self.cleaned_data.get("username") #获取输入的username的值 if "admin" in value: #如果包含了admin raise ValidationError("用户名不能含有敏感信息") #则返回错误信息 def test(request): if request.method == ‘GET‘: u_obj = UserInfo() return render(request, ‘test.html‘, {‘u_obj‘: u_obj}) else: u_obj = UserInfo(request.POST) if u_obj.is_valid(): print(u_obj.cleaned_data) return HttpResponse(‘检验通过‘) else: print(u_obj.errors) return render(request, ‘test.html‘, {‘u_obj‘: u_obj})
上面是在class的内部定义方法,还可以在class类的外部定义函数,如下:
from django.shortcuts import render,HttpResponse from django import forms from django.core.exceptions import ValidationError #校验错误 #自定义一个校验的函数,如果长度大于6,则抛出错误信息 def max_num(n): if len(n) > 6: raise ValidationError(‘太长了‘) class UserInfo(forms.Form): username = forms.CharField( label=‘用户名‘, required=True, #validators:自定义校验 validators=[max_num] #在此处使用自定义的函数,检验时,会自动将输入的值作为参数传入函数中,并进行校验和返回错误信息 ) password = forms.CharField( label=‘密码‘, widget=forms.widgets.PasswordInput(render_value=True) ) def test(request): if request.method == ‘GET‘: u_obj = UserInfo() return render(request, ‘test.html‘, {‘u_obj‘: u_obj}) else: u_obj = UserInfo(request.POST) if u_obj.is_valid(): print(u_obj.cleaned_data) return HttpResponse(‘检验通过‘) else: print(u_obj.errors) return render(request, ‘test.html‘, {‘u_obj‘: u_obj})