1、安装django-simple-captcha
pip install django-simple-captcha
2、打开settings.py在INSTALLED_APPS中配置
INSTALLED_APPS = [
'captcha',
]
3、打开urls.py在urlpatterns中配置url
urlpatterns = [
path('captcha',include('captcha.urls')),
]
4、迁移同步,生成captcha所依赖的表
python manage.py makemigrations
python manage.py migrate
5、将captcha字段在form类当中进行设置
from django import forms
from captcha.fields import CaptchaField
class UserRegisterForm(forms.Form):
email = forms.EmailField(required=True)
password = forms.CharField(required=True,min_length=3,max_length=15,error_messages={
'required':'密码必须填写',
'min_length':'密码不得小于3位',
'max_length':'密码不得大于15位'
})
captcha = CaptchaField(error_messages={
'invalid': '验证码错误'
})
6、后台逻辑里面,在get请求中实例化form,将form对象返回到页面
def user_register(request):
if request.method == 'GET':
user_register_form = UserRegisterForm()
return render(request,'register.html',{
'user_register_form':user_register_form
})
7、在前端页面上通过{{ user_register_form.captcha }}获取验证码