美文网首页
django 添加验证码2

django 添加验证码2

作者: LEUNGJH | 来源:发表于2018-03-21 15:52 被阅读0次

部署环境:

Centos 6.5  /   python2.6   /    django1.6

1、安装 django-simple-captcha

# pip install django-simple-captcha==0.4.6

安装Pillow库(Pillow-2.6.1),版本不对会生成不了图片报错:

ImportError: The _imagingft C module is not installed

想测试能不能生成图片可以到我上一篇文章调用生成验证码图片脚本

2、添加captcha到项目的setting.py文件INSTALLED_APPS

CAPTCHA_IMAGE_SIZE = (80, 33)

CAPTCHA_FOREGROUND_COLOR = '#001100'

CAPTCHA_NOISE_FUNCTIONS = ('captcha.helpers.noise_dots',)

CAPTCHA_TEST_MODE = False

3、同步数据库结构

django1.6版本执行 python manage.py syncdb

django1.6以后的版本执行 python manage.py migrate

4、添加到项目url.py

urlpatterns = [

....

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

]

5、forms.py

from django import forms

from captcha.fields import CaptchaField

class CaptchaTestModelForm(forms.Form):

    captcha = CaptchaField()

6、添加到视图view.py(具体根据自己实际情况配置)

import forms

def some_view(request):

    if request.POST:

        form = forms.CaptchaTestForm(request.POST)

        # Validate the form: the captcha field will automatically

        # check the input

        if form.is_valid():

            human = True

    else:

        form = forms.CaptchaTestModelForm()

    return render_to_response('template.html',locals())

7、添加到template.html

{{ form.captcha }}

8、点击刷新

关联一个JQ文件,然后添加代码

$('.captcha').click(function(){

        console.log('click');

        $.getJSON("/captcha/refresh/",

                  function(result){

            $('.captcha').attr('src', result['image_url']);

            $('#id_captcha_0').val(result['key'])

          });

    });

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

相关文章

网友评论

      本文标题:django 添加验证码2

      本文链接:https://www.haomeiwen.com/subject/mmtbqftx.html