1. 程式人生 > >django項目中的驗證碼模塊

django項目中的驗證碼模塊

字母 註冊表 路由 required users python content session file

1、安裝驗證碼模塊:

pip install django-simple-captcha==0.4.6

2、驗證碼模塊註冊到django setting.py中的 INSTALLED_APPS:

# 註冊app的配置
INSTALLED_APPS = [
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles
, users, courses, operation, organzation, crispy_forms, xadmin, # 驗證碼模塊 captcha, ]

3、同步數據庫,把驗證碼相關的表遷移到本地數據庫:

python manage.py makemigrations
python manage.py migrate

4、添加驗證碼的url到django路由系統:

url(r^captcha/, include(captcha.urls))

5、使用captcha自帶的field生成input標簽,使用django的模板語言,部署到前端頁面:

from captcha.fields import CaptchaField
# 註冊表單驗證 
class RegisterForm(forms.Form):
    email = forms.EmailField(error_messages={required: 郵箱為必填項}, required=True)
    password = forms.CharField(error_messages={required: 密碼為必填項, min: 密碼限制為6-18位, max: 密碼限制為6-18位},
                               required
=True, max_length=18, min_length=6) # 驗證碼自帶的Field captcha = CaptchaField(error_messages={invalid: u驗證碼輸入錯誤})

6、驗證碼驗證邏輯:

  每次生成一個驗證碼,數據庫就會保存相應的字母,並生成一段hashkey,hashkey會在一個隱藏的input標簽中,隨著用戶提交表單,一起發送到後端驗證,後端會根據驗證碼和這段hashkey進行組合驗證。

django項目中的驗證碼模塊