环境的准备
前端框架semantic ui
Python 3.6.4
pip install django
pip install django-simple-captcha
django-simple-captcha官方文档地址
http://django-simple-captcha.readthedocs.io/en/latest/
目标展示
配置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
配置form.py
class LoginForms(forms.Form):
email = forms.CharField(label="邮箱", max_length=128)
password = forms.CharField(label="密码", max_length=128, widget=forms.PasswordInput)
captcha = CaptchaField()
配置views.py
def login(request):
pass
# 图片验证码
# hashkey验证码生成的秘钥,image_url验证码的图片地址
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
login_form = forms.LoginForms()
# Python内置了一个locals()函数,它返回当前所有的本地变量字典
return render(request, 'user/login.html', locals())
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代码
<script>
$('#js-captcha-refresh').click(function(){
{# $form = $(this).parents('form');#}
$.getJSON($(this).data('url'), {}, function(json) {
// This should update your captcha image src and captcha hidden input
});
return false;
});
</script>
这种刷新验证码的方式是点击按钮,还有ajax请求的刷新方式,大家有兴趣可以根据官方文档研究一下
来源:oschina
链接:https://my.oschina.net/u/1391889/blog/1623597