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 }}擷取驗證碼