-
常用的函数
-
from django.core.validators import RegexValidator用来写正则的
-
from django.core.exceptions import ValidationError用来捕获clean异常的
-
from django import forms 用来继承的
-
from django.forms import fields 用来调用字段的
-
from django.forms import widgets 用来引入页面插件的
-
注意点
-
验证码判断
首先我们将验证是储存在session中,而session是在request中,这里我们需要构造一个继承的函数,给我们form表单函数加入一个属性
class Base(object):
def __init__(self,request,*args,**kwargs):
self.request = request
super(Base,self).__init__(*args,**kwargs)
一、思路
-
用clean判断用户名密码是否正确
- 首先去数据库查用户名密码是否存在
- 如果不存在
raise ValidationError('用户名密码错误')
捕获异常 - 如果存在判断用户是否勾选持久登陆状态
- 未勾选时我们在写session最好给session一个钥匙,在吧session分装
self.request.session['is_login'] = True
self.request.session['userinfo'] = obj_login
- 勾选了就给对应的session赋值
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
check_box = self.cleaned_data['check_box']
obj_login = models.UserInfo.objects.\
filter(username=username,password=password).\
values('nickname','email','avatar').first()
if not obj_login:
raise ValidationError('用户名密码错误')
else:
self.request.session['is_login'] = True
self.request.session['userinfo'] = obj_login
print('未勾选',check_box)
if check_box:
print(check_box)
self.request.session.set_expiry(60 * 60 * 24 * 7)
return self.cleaned_data
-
用clean_name 判断验证码是否正确
整体的代码
class loginform(Base,forms.Form):
username = fields.CharField(
error_messages={'required':'请输入用户名'},
widget = widgets.TextInput(attrs={'class':"form-first-name form-control"})
)
password = fields.CharField(
error_messages={'required':"请输入密码"},
widget = widgets.PasswordInput(attrs={'class': "form-last-name form-control"})
)
check_code = fields.CharField(
error_messages={'required': "请输入验证码"},
)
check_box = fields.CharField(
required=False,
widget = widgets.CheckboxInput({'value':"0"})
)
def clean_check_code(self):
v = self.cleaned_data['check_code']
if self.request.session.get('CheckCode').upper() != v.upper():
raise ValidationError('验证码错误')
return v
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
check_box = self.cleaned_data['check_box']
obj_login = models.UserInfo.objects.\
filter(username=username,password=password).\
values('nickname','email','avatar').first()
if not obj_login:
raise ValidationError('用户名密码错误')
else:
self.request.session['is_login'] = True
self.request.session['userinfo'] = obj_login
print('未勾选',check_box)
if check_box:
print(check_box)
self.request.session.set_expiry(60 * 60 * 24 * 7)
return self.cleaned_data
网友评论