def getvcode(request):
position=string.ascii_letters+string.digits
vcode=''.join(random.sample(position,4))
# 保存验证码
request.session['vcode']=vcode
# 生成画布
image=Image.new('RGB',(150,50),color=getrandomcolor())
# 创建画笔
draw=ImageDraw.Draw(image)
# 生成验证码
path=os.path.join(BASE_DIR,'static','fonts','ADOBEARABIC-BOLD.OTF')
font=ImageFont.truetype(font=path,size=50)
for i in range(len(vcode)):
draw.text((15+30*i,2),vcode[i],fill=getrandomcolor(),font=font)
# 生成噪声(500个不同颜色的点):
for i in range(500):
positions = (random.randint(0, 150), random.randint(0, 50))
draw.point(positions,fill=getrandomcolor())
# 创建字节容器
buffer=io.BytesIO()
# 将画布丢入容器
image.save(buffer,'png')
return HttpResponse(buffer.getvalue(),'image/png')
def getrandomcolor():
red=random.randint(0,255)
green = random.randint(0, 255)
black = random.randint(0, 255)
return (red,green,black)
在前端点击验证码切换:
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#image').click(function () {
$(this).attr('src',"/app/getvcode"+Math.random())
})
})
</script>
<body>
<form method="post" action="{% url 'app:registe' %}" enctype="multipart/form-data">
{% csrf_token %}
用户名:
<input type="text" placeholder="enter uname" name="uname"><br>
密码:
<input type="password" placeholder="enter password" name="upwd"><br>
再次输入密码:
<input type="password" placeholder="enter password" name="upwd2"><br>
<img id='image' src="/app/getvcode"><br>
验证码:
<input type="text" placeholder="enter vcode" name="vcode"><br>
<input type="file" name="uicon"><br>
<input type="submit" value="注册">
</form>
</body>