Django Simple Captcha的使用

Django Simple Captcha的使用

1、下载Django Simple Captcha

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

2、配置settings

# 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 
# 验证码宽度和高度
# CAPTCHA_IMAGE_SIZE = (100, 25)

3、配置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()

4、配置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())

5、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>

6、ajax刷新验证码

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
    $('.captcha').click(function () {
        $.getJSON("/captcha/refresh/", function (result) {
            $('.captcha').attr('src', result['image_url']);
            $('#id_captcha_0').val(result['key'])
        });

    });
</script>

 

posted @ 2019-08-13 00:47  与鹿逐秋  阅读(1848)  评论(3编辑  收藏  举报