登录验证+验证码

验证码示例:

我使用的是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用户认证的时候,要创建一个超级用户

猜你喜欢

转载自www.cnblogs.com/liujie12/p/12704256.html