直接安装:pip install django-simple-captcha
Django自动帮我们安装了相关的依赖库six
、olefile
和Pillow
,其中的Pillow是大名鼎鼎的绘图模块。
注册captcha
在settings中,将‘captcha’注册到app列表里:
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘login‘,
‘captcha‘,
]
captcha需要在数据库中建立自己的数据表,所以需要执行migrate命令生成数据表:
python manage.py migrate
根目录下的urls.py文件中增加captcha对应的网址:
如果上面都OK了,就可以直接在我们的forms.py文件中添加CaptchaField了。
需要提前导入from captcha.fields import CaptchaField
,然后就像写普通的form字段一样添加一个captcha字段就可以了!
由于我们前面是手动生成的form表单,所以还要修改一下,添加captcha的相关内容,如下所示:
这里额外增加了一条{{ login_form.captcha.errors }}
用于明确指示用户,你的验证码不正确
对于刷新验证码
修改login.html:
<div class="form-group">
{{login_form.captcha.label_tag}}<a id="refesh">刷新</a>
<p>
{{login_form.captcha}}
{{login_form.captcha.errors}}</p>
</div>
JS:
//验证码动态刷新实现
$(‘#refesh‘).click(function () {
$.getJSON("/captcha/refresh/", function (result) {
$(‘.captcha‘).attr(‘src‘, result[‘image_url‘]);
$(‘#id_captcha_0‘).val(result[‘key‘])
});
});
//后端返回验证失败后的动作
if(‘{{ status }}‘ == ‘error‘){
alert("验证失败,请重新登录!");
window.location.assign("/accounts/login/")
}
原文:https://www.cnblogs.com/cou1d/p/12079164.html