场景需求: django 有自带的设置session 时间,默认所有登入都是按系统设置的session过期时间。但是有时候借用别人的电脑不希望session过期时间太长,所以自定制(记住密码)设置,如果选中记住密码,session过期时间为一个月,否则使用默认60分钟过期。
自带session过期时间设置,在settings中:
SESSION_COOKIE_AGE = 60 * 60 # 过期时间60分钟
step1: 修改login页面,可以选择继承simpleui的方式,我先直接在simpleui 源码上改。 file_patch:simpleui/templates/admin/login.html
step2: 修改login的用户认证 file_path: 随便找一个位置,新建文件
class CustomAuthenticationForm(AuthenticationForm):
def __init__(self, request=None, *args, **kwargs):
"""
The 'request' parameter is set for custom auth use by subclasses.
The form data comes in via the standard 'data' kwarg.
"""
self.request = request
self.session = request.session
self.remember = request.POST.get("remember")
self.user_cache = None
super().__init__(*args, **kwargs)
# Set the max length and label for the "username" field.
self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
self.fields['username'].max_length = self.username_field.max_length or 254
if self.fields['username'].label is None:
self.fields['username'].label = capfirst(self.username_field.verbose_name)
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username is not None and password:
self.user_cache = authenticate(self.request, username=username, password=password)
if self.user_cache is None:
# 自定制用户认证
pass
if self.user_cache is None:
raise self.get_invalid_login_error()
else:
self.confirm_login_allowed(self.user_cache)
if self.remember:
# 如果选中记住密码,设置过期时间为一个月,否则默认60分钟
self.session.set_expiry(60 * 60 * 24 * 30)
return self.cleaned_data