在很多时候,我们都需要用到验证码,python的Pillow模块可以帮助我们绘制二维码,但是这种方法需要你事先了解Pillow模块,更方便的方法是直接使用django的第三方库 django-simple-captcha 模块。
安装该模块只需要:
pip install django-simple-captcha
captcha模块结合form表单使用非常方便,使用方法如下:
forms.py文件:
from django import forms
from captcha.fields import CaptchaField #记得导入该字段
class UserForm(forms.Form):
username = ... #这里省略具体代码
password = ...
captcha = CaptchaField(label='验证码') #重点在这里
urls.py文件:
from django.urls import path,include
from captcha.views import captcha_refresh #记得导入
urlpatterns = [
... #这里省略若干与本例不相关的url
path('captcha/',include('captcha.urls')),
path('refresh/',captcha_refresh),
]
captcha.views 内置就有刷新验证码的方法,因此我们不必再自己去写了,非常方便。
模板文件下:
<script>
$('.captcha').click(function () {
$.getJSON('/captcha/refresh/',function (result) {
$('.captcha').attr('src',result['image_url']);
$('#id_captcha_0').val(result['key']);
});
});
</script>
只需要上述几行代码,其它地方均不需要改动,验证码即可刷新。