驗證碼示例:
我使用的是sqlite3數據庫存儲數據
urls.py
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
#使用FBV來寫的格式
path('login/', views.Login.as_view()),
path('get_valid_pic/', views.get_valid_pic),
path('index/', views.index),
]
views.py
from django.shortcuts import render,redirect,HttpResponse
from django.http import JsonResponse
# Create your views here.
from django.views import View
from django.contrib import auth
from django.contrib.auth.decorators import login_required
class Login(View):
def get(self,request):
return render(request,'login.html')
def post(self,request):
username = request.POST.get('username')
password = request.POST.get('password')
valid_code = request.POST.get('valid_code')
valid_str = request.session.get('valid_str')
#以后向ajax中傳數據最好都使用一個字典
res = {'state':False,'msg':None}
if valid_code.upper() == valid_str.upper():
#用戶認證
user = auth.authenticate(username=username,password=password)
auth.login(request,user)
if user:
res['state'] = True
else:
res['msg'] = '用戶名密碼錯誤!'
else:
res['msg'] = '驗證碼錯誤'
return JsonResponse(res)
def get_valid_pic(request):
from PIL import Image,ImageDraw,ImageFont
import random
#生乘隨機的RGB
def random_color():
return (random.randint(0,255),random.randint(0,255),random.randint(0,255))
#生成隨機背景色 對象
image = Image.new("RGB",(270,37),random_color())
#給圖片添加內容
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("static/fontAwesome/fonts/song.ttf", 28)
temp = []
for i in range(5):
random_low = chr(random.randint(97,122))
random_upper = chr(random.randint(65,90))
random_digit = str(random.randint(0,9))
random_choose = random.choice([random_low,random_upper,random_digit])
draw.text((40+40*i,0),random_choose,random_color(),font=font)
temp.append(random_choose)
# 在內存中生成圖片
from io import BytesIO
f = BytesIO()
image.save(f, "png")
data = f.getvalue()
f.close()
valid_str = ''.join(temp)
request.session['valid_str'] = valid_str
return HttpResponse(data)
#這個裝飾器實現的功能是,之前登錄過index的可以直接登錄,沒登錄過的就跳轉到login頁面 #注意要在settings.py中 LOGIN_URL = '/login/' # 這里配置成你項目登錄頁面的路由
@login_required
def index(request):
return render(request,'index.html')
login.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>登錄界面</title> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load static %} <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'fontAwesome/css/font-awesome.min.css' %}"> <link rel="stylesheet" href="{% static 'sweetalert/sweetalert.css' %}"> <style> .container { margin-top: 100px; } </style> </head> <body> <div class="container"> <div class="row"> <form action="" class="col-md-6 col-md-offset-3"> <div class="form-group"> <label for="username">用戶名</label> <input type="text" class="form-control" id="username" placeholder="username"> </div> <div class="form-group"> <label for="password">密碼</label> <input type="password" class="form-control" id="password" placeholder="password"> </div> <label for="valid_code">驗證碼</label> <div class="row form-group"> <div class="col-md-6"> <input type="text" class="form-control" id="valid_code"> </div> <div class="col-md-6"> <img width="270px" height="37px" src="/get_valid_pic/" alt=""> </div> </div> <input type="button" class="btn btn-default" value="登錄" id="btn"> <span style="margin-left: 20px;color: red" class="error"></span> </form> </div> </div> <script src="{% static 'jquery-3.2.1.min.js' %}"></script> <script src="{% static 'setupajax.js' %}"></script> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> <script src="{% static 'sweetalert/sweetalert.min.js' %}"></script> <script> {# 使用AJAX給登錄按鈕綁定事件#} $("#btn").on("click",function () { $.ajax({ url:'', type:"POST", data:{ username:$("#username").val(), password:$("#password").val(), valid_code:$("#valid_code").val() }, success:function (arg) { if (arg.state){ location.href="/index/" } else{ $('.error').text(arg.msg) } } }) }) </script> </body> </html>
index.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>index</title> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load static %} <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'fontAwesome/css/font-awesome.min.css' %}"> <link rel="stylesheet" href="{% static 'sweetalert/sweetalert.css' %}"> </head> <body> <h1>hello,{{ request.user.username }}</h1> <script src="{% static 'jquery-3.2.1.min.js' %}"></script> <script src="{% static 'setupajax.js' %}"></script> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> <script src="{% static 'sweetalert/sweetalert.min.js' %}"></script> </body> </html>
注意:
在使用auth用戶認證的時候,要創建一個超級用戶
點擊驗證碼刷新功能
<script> {# 驗證碼刷新#} //綁定要刷新的對象 $("#valid_img").on("click",function () { //先把js對象轉化成dom對象,在后面加上?就相當於在此訪問 $(this)[0].src+="?"; }) </script>