Django之自带认证

时间:2022-06-20 10:44:29

自带登录实例

{% extends "layout/base.html" %}  // 所有link

{% block body %}
<div id="container" class="cls-container"> <!-- BACKGROUND IMAGE -->
<!--===================================================-->
<div id="bg-overlay" class="bg-img" style="background-image: url(img/bg-img-3.jpg)"></div> <!-- LOGIN FORM -->
<!--===================================================-->
<div class="cls-content">
<div class="cls-content-sm panel">
<div class="panel-body">
<div class="mar-ver pad-btm">
<h1 class="h3">LuffyAudit 堡垒机</h1>
<p>Sign In to your account</p>
</div>
<form method="POST">{% csrf_token %}
<div class="form-group">
<input type="text" name="username" class="form-control" placeholder="Username" autofocus>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password">
</div> <button class="btn btn-primary btn-lg btn-block" type="submit">Sign In</button>
<span style="color:red;">{{ error }}</span>
</form>
</div> <div class="pad-all">
<a href="#" class="btn-link mar-rgt">Forgot password ?</a>
<a href="#" class="btn-link mar-lft">Create a new account</a> </div>
</div>
</div>
<!--===================================================--> </div>
<!--===================================================-->
<!-- END OF CONTAINER --> {% endblock %}

login.html

from django.db import models
from django.contrib.auth.models import User class Account(models.Model):
"""
堡垒机账户
1.扩展
2.继承
"""
user = models.OneToOneField(User, models.CASCADE)
name = models.CharField(max_length=64)

models.py

LOGIN_URL = '/login/'

settings.py

from django.shortcuts import render,redirect,HttpResponse
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required # @login_required(login_url='/login/') # 单独添加login页面的url
# 或在settings.py设置全局LOGIN_URL = '/login/'
@login_required
def index(request):
return HttpResponse("成功登录index页面!")
return render(request,"index.html") def acc_login(request):
error = ''
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username,password=password) # 认证
if user:
login(request,user) # 登录
return redirect(request.GET.get('next') or "/index/") # 若有next字段,则跳转到该url,否则index页面
else:
error = "Wrong username or password" return render(request,"login.html",{"error":error}) @login_required
def acc_logout(request):
logout(request) # 登出
return redirect("/login/")

views.py

结果:

单独登录login页面

Django之自带认证

直接访问index页面,views里的login_required装饰器会跳转到login页面,同时会带有?next=/index/字段的url

此处需在login函数里配置

return redirect(request.GET.get('next') or "/index/")

Django之自带认证

成功登录

Django之自带认证