菜鸟学Python之django-simple-captcha使用

环境的准备

前端框架semantic ui
Python 3.6.4

pip install django  
pip install django-simple-captcha

django-simple-captcha官方文档地址
http://django-simple-captcha.readthedocs.io/en/latest/

目标展示

输入图片说明

配置settings.py

# django_simple_captcha 验证码配置其他配置项查看文档
# 默认格式
CAPTCHA_OUTPUT_FORMAT = '%(image)s %(text_field)s %(hidden_field)s '
CAPTCHA_NOISE_FUNCTIONS = ('captcha.helpers.noise_null', # 没有样式
    # 'captcha.helpers.noise_arcs', # 线
    # 'captcha.helpers.noise_dots', # 点
)
# 图片中的文字为随机英文字母,如 mdsh
# CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge' 
 # 图片中的文字为数字表达式,如2+2=
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'   
# 超时(minutes)
CAPTCHA_TIMEOUT = 1 

配置form.py

class LoginForms(forms.Form):
    email = forms.CharField(label="邮箱", max_length=128)
    password = forms.CharField(label="密码", max_length=128, widget=forms.PasswordInput)
    captcha = CaptchaField()

配置views.py

def login(request):
    pass
   # 图片验证码
    # hashkey验证码生成的秘钥,image_url验证码的图片地址
    hashkey = CaptchaStore.generate_key()
    image_url = captcha_image_url(hashkey)
    login_form = forms.LoginForms()
    # Python内置了一个locals()函数,它返回当前所有的本地变量字典
    return render(request, 'user/login.html', locals())

html 模板中显示验证码

        <div class="field">
          <div class="ui left img input">
            <button  id='js-captcha-refresh'  class='ui icon button ' ><i class="refresh icon green"></i></button>
              <img src="{{ image_url}}" alt="captcha" class="captcha">
              <input autocomplete="off" id="id_captcha_1" name="captcha_1" type="text" placeholder="输入验证码">
              <input id="id_reg_captcha_0" name="captcha_0" type="hidden" value="{{ hashkey }}">
          </div>
        </div>

在模板中加入js代码

<script>
  $('#js-captcha-refresh').click(function(){
{#    $form = $(this).parents('form');#}

    $.getJSON($(this).data('url'), {}, function(json) {
        // This should update your captcha image src and captcha hidden input

    });

    return false;
});
  </script>

这种刷新验证码的方式是点击按钮,还有ajax请求的刷新方式,大家有兴趣可以根据官方文档研究一下

转载于:https://my.oschina.net/hellotest/blog/1623597

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值