需要check_code.py (外部)
需要Pillow模块
需要Monaco.ttf字体文件 (外部)
在app01中新建account.py
account.py
# -*- coding:utf-8 -*-
from django.shortcuts import HttpResponse
from app01 import check_code
from io import BytesIO
def check_code111(request):
img, code = check_code.create_validate_code() #执行check_code文件内的create_validate_code()方法
stream = BytesIO() #建立一个内存区域
img.save(stream, 'PNG') #以PNG格式存入内存
request.session['Check_code'] = code #验证码存入session
return HttpResponse(stream.getvalue()) #把生成的图片返回给img
urls.py
*** img 的src 映射过来的的是一个网页***
from django.conf.urls import url
from django.contrib import admin
from app01 import views
from app01 import account
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.login, name='login'),
url(r'^index/$', views.index, name='index'),
url(r'^check_code.html$', account.check_code111),
]
views.py
from django.shortcuts import render, redirect
# Create your views here.
def login(request):
if request.method == 'POST':
u = request.POST.get('username')
p = request.POST.get('password')
c = request.POST.get('code')
if c.upper() == request.session.get('Check_code').upper(): #比较输入的验证码与生成图片时存入的验证码是否一致
res = redirect('/index/')
res.set_cookie('user', u)
res.set_cookie('pass', p)
return res
else:
return render(request, 'login.html')
else:
return render(request, 'login.html')
def index(request):
u = request.COOKIES.get('user')
p = request.COOKIES.get('pass')
return render(request, 'index.html', {'u':u, 'p':p})
template---login.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
<p>username:<input type="text" name="username"></p>
<p>password<input type="password" name="password"></p>
<p><input type="text" placeholder="check_code" name="code"> ![](check_code.html)</p>
<!--***注意此处src="check_code.html"-->
<p><input type="submit" value="submit"></p>
</form>
</body>
<script>
function img111(ths){
ths.src = ths.src + '?'
}
</script>
</html>
template---index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>OK</h1>
user:{{ u }}
pass:{{ p }}
</body>
</html>
网友评论