django-simple-captcha与ajax的交互用法

django-sample-captcha文档地址:https//django-simple-captcha.readthedocs.io/en/latest/usage.html

在实际生活中,常会遇到验证码,验证码技术阻挡了不少的恶意的爬取,当然,反爬技术也是与时俱进.django在实现验证码的上,有一个第三方的库,安装方式如下:

pip install django-simple-captcha

功能可以说很强大,可以满足日常的需要,内置多种验证的形式,如加减法,英文,数字等。

一般用法:

先在设置中注册应用

再在URL中配置

url(r'^captcha/', include('captcha.urls')),

在相应的forms.py文件中,

from captcha.fields import CaptchaField
captcha = CaptchaField(error_messages={"invalid": "验证码错误"},)

接着在模板中使用

{{形式}}或者具体的{{login_form.captcha}},刷新页面就会有一个验证码,但是每次使用都需要刷新,非常不方便,体验性也差。

有什么办法解决。

使用AJAX刷新

先分析页面中的验证码。

验证码只是改变了IMG SRC中的地址和ID = “id_reg_captcha_0” 中值的值,改变这两个值就可以改变验证码。

但使用上面的普通方式很难使用改变,并且验证码的样式也不好定制。那么可以考虑自定义表单,只需要在后端产生图片和键就可以很方便定制。

url.py:

from students.views import refresh_captcha
url(r'refresh/$', refresh_captcha, name='captcha-refresh')

views.py

from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url


def get(self, request):
        login_form = LoginForm()
        hashkey = CaptchaStore.generate_key() # 验证码的key
        # 图片地址
        imgage_url = captcha_image_url(hashkey)
        return render(request, 'index.html', {"login_form": login_form, "hashkey": hashkey, "imgage_url": imgage_url})

def refresh_captcha(request):
    to_json_response = dict()
    to_json_response['status'] = 1 # ajax的状态
    to_json_response['new_cptch_key'] = CaptchaStore.generate_key() 
    to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')

在文档中,这一块代码比较多,但核心代码就只需要钥匙和地址。

AJAX代码:

$('.next-captcha').click(function () {
    $.getJSON("{% url 'captcha-refresh' %}", function (result) {
        $('.captcha').attr('src', result['new_cptch_image']);
        $('#id_reg_captcha_0').val(result['new_cptch_key'])
    });
});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值