
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from myadmin.models import User
def verify(request):
import random
from PIL import Image, ImageDraw, ImageFont
bgcolor = (242, 164, 247)
width = 100
height = 25
im = Image.new('RGB', (width, height), bgcolor)
draw = ImageDraw.Draw(im)
for i in range(0, 100):
xy = (random.randrange(0, width), random.randrange(0, height))
fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
draw.point(xy, fill=fill)
str1 = '0123456789'
rand_str = ''
for i in range(0, 4):
rand_str += str1[random.randrange(0, len(str1))]
font = ImageFont.truetype('static/arial.ttf', 21)
fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
draw.text((5, -3), rand_str[0], font=font, fill=fontcolor)
draw.text((25, -3), rand_str[1], font=font, fill=fontcolor)
draw.text((50, -3), rand_str[2], font=font, fill=fontcolor)
draw.text((75, -3), rand_str[3], font=font, fill=fontcolor)
del draw
request.session['verifycode'] = rand_str
"""
python2的为
import cStringIO
buf = cStringIO.StringIO()
"""
import io
buf = io.BytesIO()
im.save(buf, 'png')
return HttpResponse(buf.getvalue(), 'image/png')
<input type="text" class="form-control" name = 'code' style="width:150px" placeholder="验证码">
<span class="form-control-feedback" style="width:150px">
<img src="{% url 'myadmin_verify' %}" onclick="this.src = '{% url 'myadmin_verify' %}?sn='+Math.random()"/>
</span>
配置路由
path('verify', index.verify, name="myadmin_verify"),
def dologin(request):
try:
if request.POST['code'] != request.session['verifycode']:
context = {"info": '验证码错误,请重新输入'}
return render(request, 'myadmin/index/login.html', context)
user = User.objects.get(username=request.POST['username'])
if user.status == 6:
import hashlib
md5 = hashlib.md5()
s = request.POST['pass'] + user.password_salt
md5.update(s.encode('utf-8'))
if user.password_hash == md5.hexdigest():
request.session['adminuser'] = user.toDict()
return redirect(reverse("myadmin_index"))
else:
context = {"info": '密码错误,请重新输入'}
else:
context = {"info": '无效的登录账号'}
except Exception as err:
print(err)
context = {"info": '登录账号不存在'}
return render(request, 'myadmin/index/login.html', context)