Login verification + verification code

Example verification code:

I am using sqlite3 database to store data

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 
    random background color object
            #User 
            authentication user = auth.authenticate (username = username, password = password) 
            auth.login (request, user) 
            if user: 
                res ['state'] = True 
            else: 
                res ['msg'] = 'Username and password are wrong ! ' 
        The else: 
            RES [' MSG '] =' codes error ' 

        return jsonResponse (RES) 

DEF get_valid_pic (Request): 
    from the PIL Import Image, ImageDraw, ImageFont 
    Import Random 
    # born by random the 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 ()) #Add 

    content to the image
    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) #The function of this decorator is that you can log in directly before logging in to the index, and jump to the login page if you have not logged in 
# Note LOGIN_URL = '/ login /' in settings.py # Configure here as the route to your project login page 
@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>

note:

  When using auth user authentication, create a super user

Guess you like

Origin www.cnblogs.com/liujie12/p/12704256.html