Verification code generation relies on the PIL library.
The code to generate the verification code is as follows:
def captcha (Request):
width = 100
Height = 40
Bg_color = (255, 255, 255)
Image = Image.new (' RGB ', (width, height), bg_color)
Font = Imagefont.truetype (' Arial.ttf ', 30)
Font_color = (0, 0, 0)
Draw = Imagedraw.draw (image)
Captcha = ' '
Alphabet = []
For I in range (48, 58):
Alphabet.append (Chr (i))
For I in range (97, 123):
Alphabet.append (Chr (i))
For I in range (65, 91):
Alphabet.append (Chr (i))
For I in range (4):
Captcha + = Random.choice (alphabet)
Draw.text ((random.randint (0), Random.randint (0,)), Captcha, Font=font, Fill=font_color)
Del Draw
New_image = image.transform (width + max, height + ten), Image.affine,
(1, -0.3, Random.randint (0, ten), -0.1, 1, random.randint (0, 10)))
New_draw = Imagedraw.draw (new_image)
Line_color = (0, 0, 0)
For I in range (0, 15):
X1 = Random.randint (0, width)
x2 = Random.randint (0, width)
Y1 = random.randint (0, height)
y2 = random.randint (0, height)
New_draw.line ([(x1, y1), (x2, y2)], Line_color)
Del New_draw
Buffer = Stringio.stringio ()
New_image.save (buffer, ' PNG ')
request.session[' captcha '] = captcha
Return HttpResponse (Content=buffer.getvalue (), content_type= "Image/png")
So, how can the generated verification code be displayed in the IMG tag of the Web page? First add Url:url (R ' ^captcha ', ' Login.captcha ') and then point the IMG src to the URL ($ (' #img_captcha '). attr (' src ', ' captcha/' + Math.random ())).
Note that usually we add a random number or timestamp to the URL to avoid the problem that the verification code does not update when the browser cache is clicked.
Django Generate verification Code