在创建Django表单时,因为需要验证用户输入的验证码是否正确,因此需要在session里提取当前验证码的值和POST提交过来的值进行比对,如图:
1 form.py 2 3 from django import forms 4 5 class LoginForms(forms.Form): 6 check_code = forms.CharField() 7 def clean_check_code(self): 8 if self.request.session.get(‘CheckCode‘).upper() != 9 self.request.POST.get(‘check_code‘).upper(): 10 raise ValidationError(message=‘验证码错误‘, code=‘invalid‘)
但是这样会引发一个AttributeError错误
因为这时的"self.request.session.get(‘CheckCode‘)"中的"self.request"指代的是表单forms(我猜的。。。),所以要继承个类BaseForm,然后在BaseForm写上
1 class BaseForm(object): 2 def __init__(self, request, *args, **kwargs): 3 self.request = request 4 super(BaseForm, self).__init__(*args, **kwargs)
原来代码改为:
1 class LoginForms(BaseForm,forms.Form): 2 check_code = forms.CharField() 3 4 def clean_check_code(self): 5 if self.request.session.get(‘CheckCode‘).upper() != self.request.POST.get(‘check_code‘).upper(): 6 raise ValidationError(message=‘验证码错误‘, code=‘invalid‘)
然后在view.py上改为:
1 from ..forms.account import LoginForms 2 3 def login(request): 4 if request.method == ‘GET‘: 5 return render(request, ‘login.html‘) 6 7 elif request.method == ‘POST‘: 8 obj = LoginForms(request = request, data = request.POST) 9 ....
原文地址:https://www.cnblogs.com/linyuhong/p/9490790.html
时间: 2024-10-11 11:04:03