Django最强大的部分之一是自动管理界面。它从模型中读取元数据,以提供一个快速的,以模型为中心的界面,受信任的用户可以在其中管理您网站上的内容。管理员的建议用法仅限于组织的内部管理工具。它并非旨在构建您的整个前端。
简单的cookie验证: 敏感信息不宜使用cookie,我们应该用cookie记录简单配置.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>
<body>
<form action="/" method="post">
<input type="text" name="username" />
<input type="button" value="获取cookie" id="get_cook"/>
<input type="button" value="设置cookie" id="set_cook"/>
<input type="submit" value="提交"/>
</form>
</body>
<script type="text/javascript">
$("#get_cook").bind("click",function(){
var cook = $.cookie("username");
$('input[name="username"]').val(cook);
});
$("#set_cook").bind("click",function(){
var cook = $('input[name="username"]').val(cook);
$.cookie("username","10");
});
</script>
</html>
from django.shortcuts import render,HttpResponse
from django.forms import Form,fields,widgets
def index(request):
if request.method == "GET":
obj = render(request,"index.html")
obj.set_cookie("username", "lyshark") # 设置一个cookie
return obj # 返回页面
else:
cook = request.COOKIES.get("username") # 获取到cookie
print("获取到cookie:{}".format(cook))
return render(request,"index.html")
使用Session进行验证:
<!--name:login.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/login/" method="post">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="用户登录"/>
</form>
</body>
</html>
# name: urls.py
from MyWeb import views
urlpatterns = [
path('login/', views.login),
path('logout/',views.logout),
path('index/',views.index)
]
# name: views.py
from django.shortcuts import render,HttpResponse,redirect
def index(request):
is_login = request.session.get("is_login",False)
if is_login:
cookie_content = request.COOKIES
session_content = request.session.get("username")
return HttpResponse("**欢迎用户 {} 你已经是登录状态,SessionID:{}:**".format(session_content,cookie_content))
else:
return redirect('/login/')
def login(request):
if request.method=="GET":
is_login = request.session.get("is_login", False)
if is_login:
cookie_content = request.COOKIES
session_content = request.session.get("username")
return HttpResponse("**欢迎用户 {} 你已经是登录状态,SessionID:{}:**".format(session_content, cookie_content))
else:
return render(request,"login.html")
elif request.method == "POST":
username = request.POST['username']
password = request.POST['password']
print(username,password)
if username == "admin" and password =="123123":
request.session['is_login'] = "True"
request.session['username'] = username
return redirect('/index/')
return render(request, "login.html")
def logout(request):
try:
del request.session['is_login']
except KeyError:
pass
return redirect("/login/")
默认的session键值对,会存储在django的数据库中,其中的配置settings.py
如下
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默认)
SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认)
SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认)
SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认)
SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认)
SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认)
SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认)
SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认)
使用auth模块实现创建用户: django为我们提供了一套完备的验证机制,如下是简单的用户创建命令.
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.contrib.auth.models import User,auth
def index(request):
if request.method == "GET":
# -------------------------------------------
# 创建用户操作
User.objects.create_user(username="lyshark",password="123123",email="lyshark@163.com") # 创建用户
User.objects.create_superuser(username="admin", password="123123", email="admin@163.com") # 创建超级用户
# -------------------------------------------
# 修改密码操作
user = User.objects.get(username="lyshark")
user.set_password(raw_password="123456")
user.save()
# -------------------------------------------
# 判断用户名密码是否有效(成功返回用户名,失败返回none)
user = auth.authenticate(username="lyshark",password="123456")
print(user)
return HttpResponse("hello lyshark")
return render(request,"index.html")
使用auth模块完成登录认证: 登录失败会自动跳转到/account/login/
你可以自定义修改LOGIN_URL=/login/
即可.
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.contrib.auth.models import User,auth
from django.contrib.auth.decorators import login_required
def login(request):
if request.method == "GET":
return HttpResponse("""
<form action="/login/" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="登陆系统">
</form>
""")
else:
username = request.POST.get("username")
password = request.POST.get("password")
# 判断用户名密码是否有效
user = auth.authenticate(username=username,password=password)
if user:
auth.login(request,user) # 执行登录函数
return HttpResponse("登陆成功.")
else:
#auth.logout(request,user) # 执行登出函数
return HttpResponse("登录失败..")
# 下方的login_required装饰器,用于验证是否登录完成
@login_required
def is_login(request):
return HttpResponse("用户已经登陆完成了...")
# 下方程序用户登出用户
def logout(request):
auth.logout(request) # 执行登出函数
return HttpResponse("用户注销完成..")
使用auth模块实现用户认证: : django为我们提供了一套完备的验证机制,如下是简单的用户创建命令.
from django.shortcuts import render,HttpResponse
from django.contrib.auth.models import User,auth
from django.contrib.auth.decorators import login_required
# 实现用户注册流程
def register(request):
if request.method == "GET":
return HttpResponse("""
<form action="/register/" method="post">
账号: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
邮箱: <input type="text", name="email"><br>
<input type="submit" value="用户注册">
</form>
""")
else:
u_username = request.POST.get("username")
u_password = request.POST.get("password")
u_email = request.POST.get("email")
# 先判断账号是否存在
if User.objects.filter(username=u_username):
return HttpResponse("{} 用户名已被注册".format(u_username))
else:
# 创建普通用户
User.objects.create_user(username=u_username, password=u_password, email=u_email)
return HttpResponse("注册 {} 成功".format(u_username))
return HttpResponse("注册出现未知错误.")
# 实现用户登录
def login(request):
if request.method == "GET":
return HttpResponse("""
<form action="/login/" method="post">
账号: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
<input type="submit" value="登陆系统">
</form>
""")
else:
u_username = request.POST.get("username")
u_password = request.POST.get("password")
# 判断用户名密码是否有效(成功返回用户名,失败返回none)
user = auth.authenticate(username=u_username, password=u_password)
if user:
# 执行用户登录函数
auth.login(request, user)
# 设置用户名session_name的一个Session
request.session['session_name'] = u_username
return HttpResponse("用户: {} 登陆成功.".format(u_username))
else:
return HttpResponse("登录失败..")
# 执行密码修改
@login_required(login_url="/login/")
def modify(request):
if request.method == "GET":
return HttpResponse("""
<form action="/modify/" method="post">
原密码: <input type="text" name="old_password"><br>
新密码: <input type="password" name="new_password"><br>
<input type="submit" value="修改密码">
</form>
""")
if request.method == "POST":
uname = request.session.get('session_name') # 先得到用户名
old_password = request.POST.get("old_password") # 得到原始密码
new_password = request.POST.get("new_password") # 设置新密码
# 判断原始用户名密码是否有效(成功返回用户名,失败返回none)
is_true = auth.authenticate(username= uname, password= old_password)
# 验证通过执行改密码
if is_true != None:
# 开始修改密码
user_obj = User.objects.get(username = uname)
user_obj.set_password(raw_password= new_password)
user_obj.save()
auth.logout(request)
return HttpResponse("用户: {} 修改密码完成,请重新登录.".format(uname))
else:
return HttpResponse("用户: {} 原始密码不正确.".format(uname))
return HttpResponse("未知错误.")
# 下方的login_required装饰器,用于验证是否登录完成,失败则跳转 /login/
@login_required(login_url="/login/")
def is_login(request):
uuid = request.session.get('_auth_user_id')
uname = request.session.get('session_name')
return HttpResponse("ID: {} 用户名: {} 已登陆.".format(uuid,uname))
# 执行用户注销操作
def logout(request):
uuid = request.session.get('_auth_user_id')
uname = request.session.get('session_name')
if uname == None:
return HttpResponse("未登录,请先登录..")
# 执行登出
auth.logout(request)
# 删除保存的用户名Session
try:
del request.session['session_name']
except KeyError:
pass
return HttpResponse("ID: {} 用户名: {} 注销完成..".format(uuid,uname))