驗(yàn)證碼的實(shí)現(xiàn)
在django中有一個(gè)專(zhuān)門(mén)實(shí)現(xiàn)驗(yàn)證碼的擴(kuò)展包---django-simple-captcha
1.安裝:
pip install django-simple-captcha
2.配置:
在MXOnline/settings.py中注冊(cè)該組件

3.在總urls.py下定義圖片驗(yàn)證碼的路由:
#圖片驗(yàn)證碼
url(r'^captcha/$',include('captcha.urls')),
也就是已經(jīng)安裝好的captcha中:

4.將該組件在mysql數(shù)據(jù)庫(kù)中生成表(數(shù)據(jù)遷移)
python manage.py makemigrations
python manage.py migrate

數(shù)據(jù)庫(kù):

5.使用
在使用這個(gè)包時(shí),要與form表單配合使用,因?yàn)楫?dāng)用戶(hù)進(jìn)行注冊(cè)時(shí),就需要圖片驗(yàn)證碼的顯示,那么我們可以將它看作一個(gè)類(lèi)似于email和password的一個(gè)字段來(lái)看。
在users/forms.py:
#注冊(cè)表單驗(yàn)證
class UserRegisterForm(forms.Form):
#email
email = forms.EmailField(required=True)
#密碼
password = forms.CharField(required=True,min_length=6,max_length=16,error_messages={
'required':'密碼必須填寫(xiě)',
'min_length':'密碼不少于6位',
'max_length':'密碼不能超過(guò)16位'
})
# 驗(yàn)證碼
captcha = CaptchaField()
添加驗(yàn)證碼字段captcha
然后由于無(wú)論是get還是post請(qǐng)求,都需要刷新驗(yàn)證碼,所以在這兩個(gè)方法中都要獲取表單實(shí)例,并返回到前端頁(yè)面。
在users/views.py中
#get方式返回register.html
def get(self, request, *args, **kwargs):
#第一次請(qǐng)求時(shí),也要訪(fǎng)問(wèn)驗(yàn)證碼,只是顯示驗(yàn)證碼
user_register_form = UserRegisterForm()
return render(request,'register.html',{
'user_register_form':user_register_form
})
#post方式處理提交的數(shù)據(jù)
def post(self,request, *args, **kwargs):
# 實(shí)例化表單,注意參數(shù)request.POST
user_register_form = UserRegisterForm(request.POST)
....
....
在前端頁(yè)面中展示驗(yàn)證碼圖片,找到驗(yàn)證碼的form表單中的標(biāo)簽:
<div class="form-group marb20 blur" id="jsRefreshCode">
{{ user_register_form.captcha }}
</div>
完成。
運(yùn)行:
輸入正確的信息:

直接登錄,并跳轉(zhuǎn)到index頁(yè)面。

輸入錯(cuò)誤信息時(shí),會(huì)彈出相應(yīng)的錯(cuò)誤信息的提示
優(yōu)化登錄
那么在login中加入驗(yàn)證碼登錄是一樣的步驟
在form表單中加入字段:
#驗(yàn)證碼
captcha = CaptchaField()
在LoginView的get和post方法中都實(shí)例化表單并返回:
get:
login_form = LoginForm() #獲取表單實(shí)例,為了展示驗(yàn)證碼
post:
login_form = LoginForm(request.POST)
在前端由于css樣式的問(wèn)題,直接將register.html中的注冊(cè)form復(fù)制到login.html中相應(yīng)位置。
修改一些參數(shù):
- active地址:login
- input標(biāo)簽中的name屬性與后端獲取的一致
- 驗(yàn)證碼展示的表單對(duì)象為login_form.captcha
運(yùn)行:
輸入正確的信息:

登錄成功

輸入驗(yàn)證碼錯(cuò)誤時(shí),不報(bào)錯(cuò),我也不知道為啥