本来想用内置的登录退出功能,结果遇到一个坑爹问题,耗掉了不少时间,还不如自己简单弄一弄。
简单说下登录退出过程
导入内置模块
from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required
登录方法,官网都有
user = authenticate(request, username=user_name, password=user_pwd) if not user is None: login(request, user)
主要 authenticate、login这个两个内置方法获取用户进行登录,数据库要有django_session这个表,用指令就可以生成 python manage.py migrate sessions
登录后,验证是否登录,还有获取登录的用户信息
if request.user.is_authenticated: name = request.user.username
最后这个问题来了,退出,千万别用 logout 这个名称作为退出的方法名称,会报下面这个错,不知道名称不能重这个问题,还真不好找出这个问题
POST http://192.168.1.1:8080/user/logout/ net::ERR_CONNECTION_RESET
退出方法
def logout_by_user(request): logout(request)
基本几个登录过程已经够了。
需要在settings.py添加几个设置,不然登录完成后session不会自动更新
SESSION_COOKIE_AGE=60*30 //过期时间
SESSION_COOKIE_AT_BROWSER_CLOSE = True
# 是否设置关闭浏览器使得Session过期
SESSION_SAVE_EVERY_REQUEST = True
# 是否每次请求都保存Session,默认修改之后才能保存
过程千千万,这只是其中最简陋的一个