这里我们使用 django-simple-captcha 模块,官方介绍如下:https://github.com/mbi/django-simple-captcha
一键安装:
pip install django-simple-captcha
在 setting.py 中把 'captcha' 加到 INSTALLED_APP 的区块中
INSTALLED_APPS = (
# ...
'captcha',
# ...
)
由于此模块会到数据库建立自己的数据表,因此要先执行数据库的 migrate 操作:
python manage.py migrate
在 urls.py 中加上这个模块对应的网址:
from django.urls import path, re_path, include urlpatterns = [
#...
url(r'^captcha/', include('captcha.urls'),
# ...
]
在窗体类中加上 CaptchaField 字段 :
from captcha.fields import CaptchaField class PostForm(forms.ModelForm):
captcha = CaptchaField() #CaptchaField 字段
class Meta:
model = models.Post
fields = ['mood', 'nickname', 'message', 'del_pass'] def __init__(self, *args, **kwargs):
super(PostForm, self).__init__(*args, **kwargs)
self.fields['mood'].label = '现在的心情'
self.fields['nickname'].label = '您的昵称'
self.fields['message'].label = '心情留言'
self.fields['del_pass'].label = '设置密码'
self.fields['captcha'].label = '请输入验证码'
运行结果如下: