Django Admin Framework plus Djangocaptcha Verification code
Introduction: This is the summary of their own work, with Django with the admin framework as the background, but the lack of verification code, so with Djangocaptcha to the admin plus the code.
<1> What is needed:
Djangocaptcha
Installation: Pip Install Djangocaptcha
<2>python Background Code
View function views.py
The View function views.py
#返回验证码图片 from
django.shortcuts import render to
django.http import HttpResponse
from Django.http Import httpresponseredirect
import Re, json from
djangocaptcha import Captcha
def code ( Request):
CA = Captcha (request)
#ca. Words = [' Hello ', ' world ', ' HelloWorld ']
ca.img_width = 150
ca.img_height =
#ca. Type = ' number '
ca.type = ' word ' return
ca.display ()
#验证, whether the submitted verification code is correct C17/>def Verifyajax (Request): Result
= ' false '
_code = Request. Get.get (' code ') or '
if not _code: Return
HttpResponse (json.dumps ([result]), content_type= ' application/ JSON ')
CA = Captcha (request)
if Ca.check (_code): Result
= ' true '
else: result
= ' false ' Return
HttpResponse (json.dumps ([result]), content_type= ' Application/json ')
<3>html Display Verification Code
<a href= "#" id= "get_code_img" ></a>
< INPUT type = "text", id = "Captcha_input", name = "Captcha_input" >
<4>js code Form Validation
Here we use jquery's Validate framework for asynchronous validation
Verify the form
$ ("#login-form"). Validate ({
rules:{
captcha_input:{
required:true,
remote:{
URL : '/accounts/verify/verifyajax ',
type: ' Get ',
dataType: ' json ',
data:{
code:function () {
Return $ ("#captcha_input"). val ();},},}}
,
messages:{
captcha_input:{
Required: "Verification code Required",
Remote: "Verification code Error",
}
},
//unauthenticated callback
Invalidhandler:function (Form, validator) {
//location.reload ();
}
});
Refresh Authenticode
$ ("#get_code_img"). Click (function () {
$ (". GetCode"). attr ("src", "/accounts/verify/code?rand=" + Math.random ());
return false;
});
$ (". GetCode"). attr ("src", "/accounts/verify/code?rand=" + math.random ());