django自带的验证机制
from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout #登入和登出 from django.contrib.auth.decorators import login_required # 验证用户是否登录 def acc_login(request): if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = authenticate(username=username,password=password) # 类型为<class 'django.contrib.auth.models.User'> # print(type(models.Customer.objects.get(name="赵凡"))) # print(user,type(user)) if user: login(request,user) # 验证成功之后登录 return redirect('/crm') return render(request, "login.html") def acc_logout(request): logout(request) # 登出 return redirect("/login")
必须登录之后才能访问页面
from django.contrib.auth.decorators import login_required @login_required # 加上这个装饰器就是限制必须登录才能执行这个函数 def dashboard(request): print(request.user) return render(request, "crm1/dashboard.html")
如果加了@login_required,页面跳转会有问题,解决方法如下
在setting里追加一下内容/login/
跟URL是一致的
LOGIN_URL = "/login/"