1.依赖
pip install django-simple-captcha
2.注册app
添加captcha到INSTALLED_APPS
INSTALLED_APPS = [
...
# 图片验证码
'captcha',
...
]
3.配置url.py
添加一个条目到您的urls.py:
urlpatterns = [
path('captcha/', include('captcha.urls')), ]
4.创建表单
创建一个forms.py文件
from django import forms
from captcha.fields import CaptchaField
class CaptchaTestForm(forms.Form):
captcha = CaptchaField()
5.在视图中实例化CaptchaTestForm对象
class LoginView(View):
...
captcha_form = CaptchaTestForm()
...
return render(request,'login.html',{'captcha_form ':captcha_form })
6.在模板中使用图片验证码
6.1在login.html中调用captcha属性
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录验证码</title>
</head>
<script src="{% static 'js/jquery.min.js' %}" type="text/javascript"></script>
<body>
验证码图片:{{ captcha_form.captcha}}
</body>
<!--ajax动态更新验证码-->
<script type="text/javascript">
$('.captcha').click(function () {
$.getJSON("/captcha/refresh/", function (result) {
$('.captcha').attr('src', result['image_url']);
$('#id_captcha_0').val(result['key'])
});
});
</script>
</html>
生成的效果图: