当前位置:   article > 正文

Python——Django框架——django-simple-captcha(验证码)

django-simple-captcha

一、引用 包

pip install django-simple-captcha

二、将captcha加入setting的 INSTALLED_APPS

三、运行python manager.py migrations 和 python manage.py migrate

四、加入路径

path('captcha/',include('captcha.urls))

五、引入Form表单

from captcha.fields import CaptchaFieldclass
captcha = CaptcchaField()#生成图片验证码和输入框

六、ajax动态验证

from django.http import JsonResponse
from captcha.models import CaptchaStore

def ajax_val(request):
    if  request.is_ajax():
        cs = CaptchaStore.objects.filter(response=request.GET['response'], hashkey=request.GET['hashkey'])
        if cs:
            json_data={'status':1}
        else:
            json_data = {'status':0}
        return JsonResponse(json_data)
    else:
        # raise Http404
        json_data = {'status':0}
        return JsonResponse(json_data)
view.py
path(r'^ajax_val/',views.ajax_val, name='ajax_val'), #动态验证的路由
  <script>
    $(function(){
    $('#id_captcha_1').blur(function(){
  // #id_captcha_1为输入框的id,当该输入框失去焦点是触发函数
        json_data={
            'response':$('#id_captcha_1').val(), // 获取输入框和隐藏字段id_captcha_0的数值
            'hashkey':$('#id_captcha_0').val()
        }
        $.getJSON('/ajax_val', json_data, function(data){
 //ajax发送
            $('#captcha_status').remove()
            if(data['status']){ //status返回1为验证码正确, status返回0为验证码错误, 在输入框的后面写入提示信息
                $('#id_captcha_1').after('<span id="captcha_status" >*验证码正确</span>')
            }else{
                 $('#id_captcha_1').after('<span id="captcha_status" >*验证码错误</span>')
            }
        });
    });
    })
    </script>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
tempalte

七、ajax刷新

path(r’refresh/$’, views.captcha_refresh, name=’captcha-refresh’)
# 只是源码介绍不用写入自己的代码中
def captcha_refresh(request):
    """  Return json with new captcha for ajax refresh request """
    if not request.is_ajax():
 # 只接受ajax提交
        raise Http404
    new_key = CaptchaStore.generate_key()
    to_json_response = {
        'key': new_key,
        'image_url': captcha_image_url(new_key),
    }
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')
view.py
    $(function(){
    $('.captcha').css({
        'cursor': 'pointer'
    })
    # ajax 刷新
    $('.captcha').click(function(){
        console.log('click');
         $.getJSON("/captcha/refresh/",
                  function(result){
             $('.captcha').attr('src', result['image_url']);
             $('#id_captcha_0').val(result['key'])
          });});
ajax刷新

 

 

 

| |

转载于:https://www.cnblogs.com/cxys85/p/10867358.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/982993
推荐阅读
相关标签
  

闽ICP备14008679号