72. supplement the simple verification code implementation of django with the form hook function, djangoform
This article mainly describes how to implement a simple verification code. The verification code is basically implemented by finding a ready-made component. To implement this simple function using the code, you can understand the internal implementation of the verification code.
Navigate to this article:
- Five verification Codes
- Code Implementation
- Logon Verification
- Form component hook function supplement
1. Five verification Codes
Ii. Code Implementation
1. Use bootstrap to deploy a simple page
<Div class = "container"> <div class = "row"> <div class = "col-md-5 col-md-offset-3"> View Code
2. Write a verification code in the view function.
First download the image processing module
pip install PILpip install pillow
If the first one cannot be downloaded, download the second one. Their reference is from PIL. There is no difference in implementation of Random verification code. Image Code:
Def get_validCode_img (request): from io import BytesIO # Memory import random from PIL import Image, ImageDraw, ImageFont img = Image. new (mode = "RGB", size = (120, 40), color = (random. randint (0,255), random. randint (0,255), random. randint (0,255) draw = ImageDraw. draw (img, "RGB") font = ImageFont. truetype ("static/font/kumo. ttf ", 25) valid_list = [] # random five-digit uppercase/lowercase letter for I in range (5): random_num = str (random. randint (0, 9) random_lower_zimu = chr (random. randint (65,90) random_upper_zimu = chr (random. randint (97,122) random_char = random. choice ([random_num, random_lower_zimu, random_upper_zimu]) draw. text ([5 + I * 24, 10], random_char, (random. randint (0,255), random. randint (0,255), random. randint (0,255), font = font) valid_list.append (random_char) f = BytesIO () img. save (f, "png") data = f. getvalue () # value in memory: valid_str = "". join (valid_list) # print (valid_str) request. session ["keepValidCode"] = valid_str # store session return HttpResponse (data)
Iii. logon Verification
1. ajax Implementation Verification
<script src="/static/jquery-3.2.1.js"></script><script> $("#subBtn").click(function () { $.ajax({ url: "/login/", type: "POST", data: { "username" : $("#username").val(), "password" : $("#password").val(), "validCode" : $("#validCode").val(), "csrfmiddlewaretoken" : $("[name='csrfmiddlewaretoken']").val() }, success: function (data) { var response = JSON.parse(data); if (response["is_login"]) { location.href = "/index/" } else { $(".error").html(response["error_msg"]).css("color", "red") } } }) })</script>
2. view Functions
Use built-in user authentication in django to import modules
from django.contrib import auth
Code
Def log_in (request): if request. is_ajax (): username = request. POST. get ("username") password = request. POST. get ("password") validCode = request. POST. get ("validCode") login_response = {"is_login": False, "error_msg": None} if validCode. upper () = request. session. get ("keepValidCode "). upper (): user = auth. authenticate (username = username, password = password) if user: login_response ["is_login"] = True request. session ["IS_LOGON"] = True request. session ["USER"] = username # auth. login (request, user) is the same as the session written in the previous two steps. else: login_response ["error_msg"] = "username or password error" else: login_response ["error_msg"] = 'validcode error' import json return HttpResponse (json. dumps (login_response) return render (request, "login.html ")
Home page view Functions
Def index (request): ret = request. session. get ("IS_LOGON", None) if ret: username = request. session. get ("USER") return render (request, "index.html", {"username": username}) return redirect ("/login/") # if not request. user. is_authenticated (): # return redirect ("/login/") # return render (request, "index.html") # With the above auth. use login (request, user) # Use {request on the template page. user. username} indicates that the user does not need to pass the value directly.
Iv. Add hook functions for Form Components
Just do a simple supplement to the hook function to see the specific Form components please go to: http://www.cnblogs.com/liluning/p/7822526.html
From django import formsclass LoginForm (forms. form): username = forms. charField (label = 'username', max_length = 100) password = forms. charField (label = 'Password', max_length = 100) # Add the judgment condition def clean_username (self): if len (self. cleaned_data.get ("username")> 5: print (self. cleaned_data.get ("password") return self. cleaned_data.get ("username") def clean_password (self): pass # global hook function def clean (self): if self. cleaned_data ["password"] = self. cleaned_data ["repeat_password"]: return self. cleaned_data