官方文档:Using django-simple-captcha — Django Simple Captcha 0.5.15 documentation
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 |
|
- 数据库同步
1 2 |
|
应用场景
- form定义
app下自定义froms.py文件,创建一个注册form
1 2 3 4 5 6 7 |
|
- views.py代码
1 2 3 4 5 6 7 |
|
- html页面引用
1 |
|
模板中引用
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'])
});
});
})
From加验证码功能
from captcha.fields import CaptchaField
class PostForm(forms.ModelForm):
captcha = CaptchaField() #CaptchaField 字段
class Meta:
model = models.Post
fields = ['mood', 'nickname', 'message', 'del_pass']
def __init__(self, *args, **kwargs):
super(PostForm, self).__init__(*args, **kwargs)
self.fields['mood'].label = '现在的心情'
self.fields['nickname'].label = '您的昵称'
self.fields['message'].label = '心情留言'
self.fields['del_pass'].label = '设置密码'
self.fields['captcha'].label = '请输入验证码'