Django-simple-captcha 验证码插件

  • 时间:
  • 来源:互联网
  • 文章标签:

官方文档:http://django-simple-captcha.readthedocs.io/en/latest/usage.html#installation

github:https://github.com/mbi/django-simple-captcha

安装部署

pip install  django-simple-captcha

settings.py配置,加入captcha

INSTALLED_APPS = [
    'captcha',
]

配置验证码模式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 

urls.py配置

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

1

2

3

4

5

6

7

from django.conf.urls import url, include

from django.contrib import admin

 

urlpatterns = [

    url(r'^admin/', admin.site.urls),

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

]

  • 数据库同步

1

2

makemigrations

migrate

应用场景

  • form定义

app下自定义froms.py文件,创建一个注册form

1

2

3

4

5

6

7

from django import forms

from captcha.fields import CaptchaField

 

class RegisterForm(forms.Form):

    email = forms.EmailField(required=True)

    password = forms.CharField(required=True, min_length=5)

    captcha = CaptchaField(error_messages={"invalid": u"验证码错误"})

  • views.py代码

1

2

3

4

5

6

7

from django.views.generic.base import View

 

class RegisterView(View):

 

    def get(self, request):

        register_form = RegisterForm()

        return render(request, "register.html", {"register_form": register_form})

  • html页面引用

1

{{ register_form.captcha }}

模板中引用

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刷新验证码,要先进入jquery

$(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'])
            });
        });
    })

 

本文链接http://www.taodudu.cc/news/show-647535.html