命令行创建超级用户
python manage.py createsuperuser
登陆验证跳转
# 局部配置# @login_required(login_url='/auth_login/')# 全局配置# auth自动跳转LOGIN_URL = '/auth_login/' # settings.py配置
可以扩展默认的用户model
from django.contrib.auth.models import AbstractUserclass Userinfo(AbstractUser): phone = models.CharField(max_length=32) avatar = models.CharField(max_length=32)# 用自己创建的表,所有auth模块的方法使用方式不变
在settings文件中设置自定制的用户模型
AUTH_USER_MODEL = 'app01.Userinfo'
操作
def auth_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') # models.User.objects.filter(username=username,password=password).first() user_obj = auth.authenticate(request,username=username,password=password) if user_obj: # 记录用户状态 # request.session['name'] = 'jason' auth.login(request,user_obj) # 一旦记录了,可以在任意的地方通过request.user获取到当前登录对象 return HttpResponse('ok') return render(request,'auth_login.html')def auth_index(request): print(request.user.is_authenticated()) # 判断当前用户是否已经登录 print(request.user,type(request.user)) # 获取当前登录用户对象 return HttpResponse('ok')def auth_logout(request): auth.logout(request) # request.session.flush() return HttpResponse('ok')def auth_register(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user_obj = auth.authenticate(request,username=username) if user_obj: return HttpResponse('当前用户已存在') # models.User.objects.create(username=username,password=password) # User.objects.create(username=username,password=password) # 不能再用create创建 # User.objects.create_user(username=username,password=password) # 创建普通用户 User.objects.create_superuser(username=username,password=password,email='123@163.com') # 创建超级用户 return render(request,'auth_register.html')def auth_password(request): print(request.user.password) is_res = request.user.check_password('jason123') # 校验密码是否一致 if is_res: request.user.set_password('666') # 设置新密码 request.user.save() # 修改密码必须save保存 不然无效 return HttpResponse('ok')
auth装饰器
from django.contrib.auth.decorators import login_required# @login_required(login_url='/auth_login/') # 局部配置@login_requireddef auth_home(request): return HttpResponse('home必须登录才能访问')@login_requireddef auth_xxx(request): return HttpResponse('xxx必须登录才能访问')
auth重置密码后,再次校验用户登录时,会清空上一次的session和浏览器的cookie,
需要用户重新登录