django已经做好用户登录及权限相关的功能,我们只需要使用就可以了。
https://docs.djangoproject.com/zh-hans/2.2/topics/auth/default/
login页面
view
from django.shortcuts import redirect
from django.views.generic.base import View, TemplateView
from django.contrib.auth import authenticate, login, logout
class LoginView(TemplateView):
template_name = 'site/login.html'
class LoginInView(View):
def post(self, request, *args, **kwargs):
username = request.POST.get('login')
password = request.POST.get('secret')
user = authenticate(request, username=username, password=password)
print(user)
if user is not None:
login(request, user)
return redirect('/backend/config/index')
else:
return redirect('/backend/login')
class LoginOutView(View):
def get(self, request, *args, **kwargs):
logout(request)
return redirect('/backend/login')
url
path('login', LoginView.as_view(), name = 'login'),
path('login-in', LoginInView.as_view(), name = 'login-in'),
path('login-out', LoginOutView.as_view(), name = 'login-out'),
页面登录验证
由于我自定义了登录页面,所以需要覆盖默认跳转登录页面。
from django.contrib.auth.mixins import LoginRequiredMixin
class BackendLoginRequiredMinix(LoginRequiredMixin):
login_url = '/backend/login'
redirect_field_name = 'redirect_to'
使用
from backend.helps.BackendLoginRequiredMinix import BackendLoginRequiredMinix
class AdvPositionIndexView(BackendLoginRequiredMinix, ListView):
model = AdvPosition # 指定模型
context_object_name = 'grid' # 默认object_list
paginate_by = 2 # 每页显示数量 默认Paginator实例 page_obj
ordering = ['-id'] # 默认排序
template_name = 'adv-position/index.html'