django登录验证码操作

import random
from PIL import Image, ImageDraw, ImageFont



def v_code(request):
    def random_color():
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
#     创建一个随机颜色的图片对象
    img_obj =Image.new('RGB',(250,30),random_color())
#     实例化一个画笔对象
    pen_obj =ImageDraw.Draw(img_obj)
#     加载字体对象
    font_obj =ImageFont.truetype('static/font/kumo.ttf',28)
    tmp = []
    for i in range(5):
        l = chr(random.randint(97, 122))  # 生成随机的小写字母
        u = chr(random.randint(65, 90))  # 生成随机的大写字母
        n = str(random.randint(0, 9))  # 生成一个随机的数字
        # 从上面三个随机选一个
        r = random.choice([l, u, n])
        pen_obj.text((40*i+30,0),r,fill=random_color(),font=font_obj)
        tmp.append(r)
    # # 加干扰线
    # width = 250  # 图片宽度(防止越界)
    # height = 35
    # for i in range(5):
    #     x1 = random.randint(0, width)
    #     x2 = random.randint(0, width)
    #     y1 = random.randint(0, height)
    #     y2 = random.randint(0, height)
    #     pen_obj.line((x1, y1, x2, y2), fill=random_color())
    #
    # # 加干扰点
    # for i in range(40):
    #     draw_obj.point([random.randint(0, width), random.randint(0, height)], fill=random_color())
    #     x = random.randint(0, width)
    #     y = random.randint(0, height)
    #     pen_obj.arc((x, y, x+4, y+4), 0, 90, fill=random_color())
    v_code=''.join(tmp).upper()
    request.session['v_code']= v_code

    # with open("static/imgs/vcode.png", "wb") as f1:
    #     img_obj.save(f1, format="PNG")
    #
    # with open("static/images/vcode.png", "rb") as f:
    #     img_data = f.read()
    # 直接在内存中保存图片替代io操作

    from  io import BytesIO
    f1 =BytesIO()
    img_obj.save(f1, format="PNG")
    img_data = f1.getvalue()
    return HttpResponse(img_data, content_type="image/png")

  在视图函数中定义此方法,在路由中添加次视图函数的调用

    url(r'^v_code/', views.v_code,name='v_code'),

在模板中添加登录控件

<div class="login-center clearfix">
                <div class="login-center-img"><img src="{% static 'imgs/password.png' %}"></div>
                <div class="login-center-input">
                    <input type="text" name="v_code" value="" placeholder="请输入验证码" onfocus="this.placeholder=''"
                           onblur="this.placeholder='请输入您的验证码'">
                    <div class="login-center-input-text">验证码</div>
                </div>
            </div>

添加验证码的更换

<script>
    img = document.getElementById('v_code');
    img.onclick = function () {
        img.src += '?'
    }
</script>

  

最重要的一点:此路由不能通过中间件的检验,因此,将此路由添加至白名单

最后完成django的登录验证码功能的添加

  

原文地址:https://www.cnblogs.com/wszxdzd/p/9917977.html