本博文源于django基础操作,旨在研究如何使用cookie登录用户。开始实验
前,如果要完成本实验所有内容,需要一些基础零件配置,可参考此博文,简单易操作。
django从零基础配置settings.py
里面包含:
其中资源路径可不配置,有以下假设
下面开始本实验!
涉及到django里的模板、视图、路由
from django.contrib import admin
from django.urls import path
from app01 import views # 新增
urlpatterns = [
path('',views.index),
path('login/',views.login),
path('index/',views.index),
path('admin/', admin.site.urls),
]
from functools import wraps
from django.http import HttpResponse
from django.shortcuts import render, redirect
# Create your views here.
from django.views import View
def login_required(func):
@wraps(func)
def inner(request,*args,**kwargs):
try :
is_login = request.get_signed_cookie(
'is_login',
salt='zhang',)
except KeyError:
return redirect('/login/')
else:
if is_login != '1':
return redirect('/login/')
ret = func(request,*args,**kwargs)
return ret
return inner
@login_required
def index(request):
return render(request,'index.html')
def login(request):
if request.method == 'POST':
user = request.POST.get('user')
pwd = request.POST.get('pwd')
if user == 'zhang' and pwd == '123':
ret = redirect('/index/')
ret.set_signed_cookie('is_login','1',salt='zhang')
return ret
else:
error = '用户名或密码错误!!'
return render(request,'login.html',locals())
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Indextitle>
head>
<body>
<h1>我是Index页面!!!!h1>
body>
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Logintitle>
head>
<body>
<form method="post" action="">
{% csrf_token %}
<p>用户名:<input type="text" name="user">p>
<p>密码:<input type="password" name="pwd">p>
<p>{{ error }}p>
<button>登录button>
form>
body>
html>
没有登陆前,搜索index页面,自动跳转login
点击确定,跳转主页面
希望博文能对大家有所帮助.!博主下一篇文章:
django2.0演示cookie登出用户界面(含测试源码)