前端代碼前端
div驗證碼框的樣式git
<div class="form-group"> <label for="pwd">驗證碼</label> <div class="row"> <div class="col-md-6"> <input type="text" class="form-control" id="valid_code"> </div> <div class="col-md-6"> <img width="270" height="36" id="valid_code_img" src="/get_validCode_img/" alt=""> //自動加載驗證碼視圖函數 </div> </div> </div>
驗證碼點擊刷新事件ajax
<script> $("#valid_code_img").click(function () { {#console.log($(this)[0]);#} $(this)[0].src += "?" }); </script>
驗證碼生成函數django
def create_img(request): img = Image.new('RGB',(270,40),color=color_yeild()) # pillow 庫PIL 生成圖片 color爲函數生成 draw = ImageDraw.Draw(img) kumo_font = ImageFont.truetype('static/font/kumo.ttf',size=32) # 字體設置 check_digit = '' for i in range(5): random_num = str(random.randint(0,9)) random_low_alpha = chr(random.randint(95, 122)) random_upper_alpha = chr(random.randint(65, 90)) random_char = random.choice([random_num, random_low_alpha, random_upper_alpha]) draw.text((i*50+20,5),random_char,color_yeild(),kumo_font) check_digit += random_char # print('check_digit',check_digit) request.session["check"] = check_digit #生成隨機5位驗證碼並存入session中 f = BytesIO() img.save(f, 'png') data = f.getvalue() # with open('wudi.png','wb') as f: # img.save(f,'png') # f = open('wudi.png','rb') # import json # data = json.dumps(img) return HttpResponse(data)
def color_yeild(): #生成隨機的顏色(255,255,255) result = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) return result
登陸的時候校驗驗證碼(d代碼只有片斷),經過ajax請求傳入request的json
valid_code = request.POST.get('valid_code', None) print('valid_code',valid_code) # print('request', request) check_true = request.session.get("check") print("check_true",check_true) if valid_code.upper() == check_true.upper(): # 去除大小寫 print(1) user = auth.authenticate(username=user,password=pwd) # 自動去djangouser表中校驗 if user: auth.login(request, user) # 至關於設置session 設置session的值user 設置完成後request.user就是全局的變量了直接能夠隨意隨時隨地的使用request.user進行取值 response['user'] = user.username else: response['msg']='密碼輸入錯誤' else: response['msg']='驗證碼錯誤' return JsonResponse(response)