Install Picture processing module PILLOW:PIP Install Pillow
Pillow Official Website: http://pillow.readthedocs.io/en/latest/
Adding views in views.py
#Verification Code fromDjango.httpImportHttpResponsedefVerifycode (Request):#introduction of drawing modules fromPILImportImage, Imagedraw, Imagefont#introduction of random function modules ImportRandom#define variables for the background color, width and height of the screenbgcolor = (Random.randrange (20, 100), Random.randrange (20, 100), 255) Width= 100Height= 25#Create a Screen objectim = Image.new ('RGB', (width, height), bgcolor)#Create a Brush objectDraw =Imagedraw.draw (IM)#call the brush's point () function to draw the noise forIinchRange (0, 100): XY=(Random.randrange (0, width), random.randrange (0, height)) Fill= (Random.randrange (0, 255), 255, Random.randrange (0, 255)) Draw.point (XY, fill=fill)#define alternate values for verification codesSTR1 ='abcd123efghijk456lmnopqrs789tuvwxyz0' #randomly select 4 values as the verification codeRand_str ="' forIinchRange (0, 4): Rand_str+=str1[random.randrange (0, Len (str1))]#Constructing font ObjectsFont = Imagefont.truetype ('Arial.ttf', 23) #Construct Font ColorFontColor = (255, random.randrange (0, 255), Random.randrange (0, 255)) #Draw 4 CharactersDraw.text (5, 2), rand_str[0], Font=font, fill=fontcolor) Draw.text ((2), rand_str[1], Font=font, fill=fontcolor) Draw.text ((2), rand_str[2], Font=font, fill=fontcolor) Draw.text ((2), rand_str[3], Font=font, fill=fontcolor)#Release Brush delDraw#Deposit session for further verificationrequest.session['Verifycode'] =Rand_str#Memory file Operations #Import Cstringio python 2 usage #buf = Cstringio.stringio () #buf = io. Stringio () ImportIo#starting with Python 3.0, the Stringio and Cstringio modules have been canceled. Replace with the Import IO moduleBUF =io. Bytesio ()#save a picture in memory with a file type of PNGIm.save (BUF,'PNG') #returns the in-memory picture data to the client, MIME type is picture PNG returnHttpResponse (Buf.getvalue (),'Image/png')
If the error OSError cannot open resource does not have this font
You can search for TTF in your own Python directory and replace it with your own absolute path example: C:/users/administrator/font/arial.ttf
Effect
========================================================================================
Configure URLs
Path (' verifycode/', Views.verifycode)
Page Display Verification Code src point to captcha URL
Python Simple Verification Code