依赖

github地址:https://github.com/mbi/django-simple-captcha

1
2
pip install django-simple-captcha

注册app

添加captcha到INSTALLED_APPS

1
2
3
4
5
6
7
8
INSTALLED_APPS = [
...
# 图片验证码
'captcha',
...
]


配置url.py

1
2
3
urlpatterns = [
path('captcha/', include('captcha.urls')), ]

创建表单

创建一个forms.py文件

1
2
3
4
5
6
7
8
9
from django import forms

from captcha.fields import CaptchaField


class CaptchaTestForm(forms.Form):
captcha = CaptchaField()


在视图中实例化CaptchaTestForm对象

1
2
3
4
5
6
7
class LoginView(View):
...
captcha_form = CaptchaTestForm()
...

return render(request,'login.html',{'captcha_form ':captcha_form })

在模板中使用图片验证码

在login.html中调用captcha属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!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>


生成的效果图: