django---驗證碼\靜態文件處理

(一)設置驗證碼 ?在views.py文件里定義驗證碼

#字體顏色隨機

def rndChar():

? ? return chr(random.randint(65, 90))

# 隨機顏色1:

def rndColor():

? ? return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 隨機顏色2:

def rndColor2():

? ? return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

def identifying(request): ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -------------定義驗證碼

? ? width = 60 * 4 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?---------定義寬

? ? height = 60 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ---------定義高

? ? image = Image.new('RGB', (width, height), (255, 255, 255)) ? ? ?------定義一個新的圖片

? ? # 創建Font對象:

? ? font = ImageFont.truetype('LiberationSans-BoldItalic.ttf', 36) ? ? ? -----定義字體

? ? # 創建Draw對象:

? ? draw = ImageDraw.Draw(image) ? ? ? ? ? -------------------定義像素

? ? # 填充每個像素:

? ? for x in range(width):

? ? ? ? for y in range(height):

? ? ? ? ? ? draw.point((x, y), fill=rndColor())

? ? # 輸出文字:

? ? codes = ' '

? ? for t in range(4):

? ? ? ? code=rndChar()

? ? ? ? codes += code

? ? ? ? draw.text((60 * t + 10, 10), code, font=font, fill=rndColor2())

? ? # 模糊:

? ? image = image.filter(ImageFilter.BLUR)

? ? #將驗證碼字符串存儲到session中 ? ? ? ? ? ? ? ? ?---------為了判斷用戶驗證碼輸入的是否正確

? ? request.session['codes'] = codes

? ? request.session.set_expiry(0)

? ? f=BytesIO() ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? --------------圖片用字節來存儲

? ? image.save(f,'jpeg') ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?------------提交圖片

? ? return HttpResponse(f.getvalue(),'image/jpeg') ? ? ? ? ? ? ?----------獲取圖片,并定義圖片的格式

(二)在登錄的方法里驗證

#判斷驗證碼

? ? userverification=request.POST.get('identifying')

? ? codes=request.session['codes']

? ? print(codes)

? ? if userverification == None or codes.upper() != userverification.upper(): ? ? ?-----如果驗證碼為空或者不符合圖片

? ? ? ? context = {'userverification_error': '驗證碼輸入錯誤'}

? ? ? ? return render(request, 'user/login.html', context)

? ??url='/user/identifying'

? ? ? ? function checkimg(abc) {

? ? ? ? ? ? abc.src=url+'?num='+new Date()

? ? ? ? }

<img src="{%url 'user:identifying'%}" alt='驗證碼' style='cursor: pointer' onclick='checkimg(this)'>


(三)處理靜態文件

?項目中的CSS、圖片、js都是靜態文件

配置靜態文件

(第一步)

在settings?文件中定義靜態內容

STATIC_URL?=?'/static/'

STATICFILES_DIRS?=?[

????os.path.join(BASE_DIR,?'static'),

]

在項目根目錄下創建static目錄,再創建當前應用名稱的目錄

/static/myapp/

?在模板中可以使用硬編碼

/static/my_app/myexample.jpg

?在模板中可以使用static編碼

{?%?load?static?from?staticfiles?%}

?

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。