django 验证码(django-simple-captcha)

 

django 验证码(django-simple-captcha)

django-simple-captcha

官方文档(含基于modelForm的用法)  https://django-simple-captcha.readthedocs.io/en/latest/usage.html

    django验证码可以使用django-simple-captcha第三方插件,这个插件使用起来十分简单。 
github传送门: 
http://django-simple-captcha.readthedocs.io/en/latest/usage.html

1,安装 
    先安装:用pip源安装 pip install django-simple-captcha 
    注:我使用的是django1.9+python2.7 我安装的captcha版本号是0.4.6,不同的版本会存在一些差异。

2,将captcha添加到INSTALL_APPS当中 
3,在urls.py中加入

urlpatterns += [
    url(r'^captcha/', include('captcha.urls')),
]

4,运行 python manage.py migrate

5,在django中使用: 
    在django中创建一个表单的类,直接使用其中的field:

from captcha.fields import CaptchaField
class RegisterForm(forms.Form):
    email = forms.EmailField(required=True,)
    password = forms.CharField(required=True, min_length=5)
    #error_messages包含验证码错误的信息的一个字典
    #下面表示的是当输入的验证码不对,在浏览器显示“验证码错误”

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

    在views中实例化表单,并且将它传给模板:

register_form = RegisterForm()#实例化表单
return render(request, "register.html", {'register_form': register_form})

    在html中应用: 
    直接引用:

{{ register_form.captcha }}

     
     
    启动一下程序,可以看到: 
这里写图片描述

原文地址:https://www.cnblogs.com/16795079a/p/10985550.html