Django的form元件——自定義校驗函式
阿新 • • 發佈:2021-09-09
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})