• Django--单表操作


    Django--单表操作

    今天就以一个学生管理系统为例,先通过pymysql这个模块,进行一个单表操作,有以下两种方式

    1. 新url的方式:直接新开一个页面进行操作
    2. ajax模态框的方式:在本页面通过模态框的方式进行操作

    需求

    1. 实现一个登录注册功能
    2. 对班级表进行增删改查

    步骤

    1. 创建一个Django项目

      通过pycharm创建新项目

    2. 进行配置

      在创建的项目的settings.py文件中,进行配置文件的更改

    3. 在static文件中引入bootstrap,js

    4. 开始写功能

      1. 添加路由
      2. 设计模板
      3. 写对应的接口函数

    添加路由

    urlpatterns = [
        url(r'^login/', login),   # 登录
        url(r'^register/', register),  # 注册
        
        # 新url方式
        url(r'^classes/', classes),  # 查询班级信息
        url(r'^add_class/', add_class), # 添加班级
        url(r'^del_class/', del_class),  # 删除班级
        url(r'^update_class/', update_class),  # 更新班级
        
        # ajax模态框方式 
        url(r'^ajax_add_class/', ajax_add_class),  # 添加
        url(r'^ajax_update_class/', ajax_update_class), # 更新
    ]
    

    登录功能

    # login.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登录</title>
        
        <!--引入bootstarp里的css样式-->
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
        <style>
            *, body {
                margin: 0;
                padding: 0;
            }
    
            .body {
                position: fixed;
                top: 0;
                right: 0;
                left: 0;
                bottom: 0;
                background: url("/static/img/5b73957e18ee0.jpg") no-repeat -20px -100px;
                background-size: 1300px;
            }
    
            .head {
                margin-top: 20px;
                margin-left: 20px;
            }
    
            .title {
                color: floralwhite;
                font-size: 40px;
                font-family: 'Consolas', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
            }
    
            .main {
                height: 350px;
                 250px;
                border: 2px solid rgba(138, 138, 138, 0.73);
                margin-top: 100px;
                margin-right: 15%;
                border-radius: 10px;
                box-shadow: 0 0 10px 0 darkgrey;
            }
    
            .main:hover {
                box-shadow: 0 10px 20px 0 black;
            }
    
            .login {
                height: 30px;
                font-size: 16px;
            }
        </style>
    </head>
    <body>
    <div class="body">
        <div class="head">
            <h1 class="title">学生管理系统</h1>
        </div>
    
        <div class="main container">
            
            <!--form表单链接,提交方式-->
            <form action="/login/" method="post" class="form-signin">
                <h3 class="form-signin-heading" style="color: #8c8c8c; margin-top: 20px;">Please sign in</h3>
                
                 <!--Useraname输入框-->
                <div style="margin-top: 20px;">
                    <span style="font-size: 14px; color: #8c8c8c;">Username</span>
                    <input type="text" name="username" class="form-control login">
                </div>
                <br>
                
                <!--Password输入框-->
                <div>
                    <span style="font-size: 14px; color: #8c8c8c;">Password</span>
                    <input type="password" name="pwd" class="form-control login">
                </div>
                <div style="margin-top: 10px;">
                    <span style="color: red; font-size: 12px;">{{ data }}</span>
                </div>
                <br>
                
                <!--提交框-->
                <input class="btn btn-primary btn-block" type="submit" value="Login">
                
                <!--连接到注册页面-->
                <button class="btn btn-success btn-block"><a href="/register/" style="color: white;text-decoration: none;">Register</a></button>
            </form>
        </div>
    </div>
    </body>
    </html>
    
    # urls.py
    
    import json
    import random
    import pymysql
    from django.conf.urls import url
    from django.shortcuts import HttpResponse, render, redirect
    
    # 连接数据库
    def mysql(sql, values=None):
        conn = pymysql.connect(
            host='127.0.0.1',
            port=3306,
            user='root',
            password='123',
            database='day55'
        )
    
        cursor = conn.cursor(pymysql.cursors.DictCursor)
    
        if not values:
            res = cursor.execute(sql)
            data = cursor.fetchall()
    
        else:
            res = cursor.execute(sql, values)
            data = cursor.fetchone()
            conn.commit()
    
        return data, res
    
    # 登录功能
    def login(request):
        
        # 判断请求方式
        if request.method == 'GET':
            
            # 通过render渲染login.html模板页面
            return render(request, "login.html")
        else:
            username = request.POST.get('username')
            pwd = request.POST.get('pwd')
    
            # 判断用户输入密码是否为空
            if not (username and pwd):
                data = '用户名密码不能为空'
                return render(request, 'login.html', {'data': data})
    
            # 判断用户是否存在
            sql = 'select * from user where name=%s'
            res = mysql(sql, (username,))[1]
            if not res:
                data = '用户名不存在,请先注册'
                return render(request, 'login.html', {'data': data})
    
            # 验证用户密码是否正确
            sql = "select pwd from user where name = %s and pwd = %s"
            res = mysql(sql, (username, pwd))[1]
    
            if res:
                obj = redirect('/classes/')
                
                # 产生一个随机的cookie
                lis = [chr(num) for num in range(48, 123) if
                       num not in [58, 59, 60, 61, 62, 63, 64, 91, 92, 93, 94, 95, 96]]
    
                val = ''
                salt = ''
                for i in range(20):
                    val += random.choice(lis)
                    salt += random.choice(lis)
    
                # 绑定加密cookie
                obj.set_signed_cookie('LOGIN', val, salt=salt, max_age=180)
                return obj
    
            else:
                data = '用户名密码错误,登录失败'
                return render(request, 'login.html', {'data': data})
    
            
    # 登录装饰器        
    def deco(func):
        def wrapper(request):
            val = request.COOKIES.get("LOGIN")
    
            if not val:
                return redirect('/login/')
    
            res = func(request)
            return res
    
        return wrapper
    

    注册功能

    # redister.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>注册</title>
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
        <style>
            *, body {
                margin: 0;
                padding: 0;
            }
    
            .body {
                position: fixed;
                top: 0;
                right: 0;
                left: 0;
                bottom: 0;
                background: url("/static/img/5b73957e18ee0.jpg") no-repeat -20px -100px;
                background-size: 1300px;
            }
    
            .head {
                margin-top: 20px;
                margin-left: 20px;
            }
    
            .title {
                color: floralwhite;
                font-size: 40px;
                font-family: 'Consolas', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
            }
    
            .main {
                height: 350px;
                 250px;
            {#background-color: black;#}{#opacity: 0.4;#} border: 2px solid rgba(138, 138, 138, 0.73);
                margin-top: 80px;
                margin-right: 15%;
                border-radius: 10px;
                box-shadow: 0 0 10px 0 darkgrey;
            }
    
            .main:hover {
                box-shadow: 0 10px 20px 0 black;
            }
    
            .login {
                height: 30px;
                font-size: 16px;
            }
        </style>
    </head>
    <body>
    <div class="body">
        <div class="head">
            <h1 class="title">学生管理系统</h1>
        </div>
    
        <div class="main container">
            <form action="/register/" method="post" class="form-signin">
                <h3 class="form-signin-heading" style="color: #8c8c8c; margin-top: 20px;">Please sign in</h3>
                <div style="margin-top: 20px;">
                    <span style="font-size: 14px; color: #8c8c8c;">Username</span>
                    <input type="text" name="username" class="form-control login">
                </div>
                <div>
                    <span style="font-size: 14px; color: #8c8c8c;">Password</span>
                    <input type="password" name="pwd" class="form-control login">
                </div>
                <div>
                    <span style="font-size: 14px; color: #8c8c8c;">Age</span>
                    <input type="password" name="age" class="form-control login">
                </div>
                <div style="margin-top: 10px;">
                    <span style="color: red; font-size: 12px;">{{ data }}</span>
                </div>
                <br>
                <input class="btn btn-primary btn-block" type="submit" value="Register">
            </form>
        </div>
    </div>
    </body>
    </html>
    
    # urls.py
    
    def register(request):
        
        # 判断请求方式
        if request.method == 'GET':
            return render(request, "register.html")
        else:
            # 获取信息post请求携带的信息
            username = request.POST.get('username')
            pwd = request.POST.get('pwd')
            age = request.POST.get('age')
    
            # 判断用户输入的是否为空
            if not (username and pwd and age):
                data = '用户名、密码、年龄不能为空'
                return render(request, 'register.html', {'data': data})
    
            # 判断用户是否存在
            sql = 'select * from user where name=%s'
            res = mysql(sql, (username,))[1]
            if res:
                data = '用户名已存在,请重新注册'
                return render(request, 'register.html', {'data': data})
            
    		# 把用户存入数据库,注册成功之后跳转到登录页面
            sql = "insert into user(name,pwd,age) values(%s,%s,%s)"
            mysql(sql, (username, pwd, age))
            return redirect('/login/')
    

    班级表的增删改查

    # classes.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>班级表</title>
        <style>
            a {
                color: black;
                text-decoration: none;
            }
    
            .shadow {
                position: fixed;
                left: 0;
                right: 0;
                top: 0;
                bottom: 0;
                background-color: black;
                opacity: 0.4;
                display: none;
            }
    
            .add_model, .update_model {
                position: fixed;
                height: 300px;
                 500px;
                left: 500px;
                top: 100px;
                background-color: white;
                display: none;
            }
    
            .model {
                margin-top: 20px;
                margin-left: 40px;
            }
    
        </style>
    </head>
    <body>
    <h2>班级表</h2>
    <!--通过table标签显示班级信息-->
    <table border="1" cellspacing="0">
        <tbody>
        <tr>
            <th>ID</th>
            <th>班级名称</th>
            <th>更新</th>
            <th>删除</th>
        </tr>
            
        <!-- 循环取出一个个元素进行展示 -->
        {% for item in classes %}
            <tr>
                <td>{{ item.id }}</td>
                <td>{{ item.cname }}</td>
                <td>
                    <button><a href="/update_class/?id={{ item.id }}">更新</a></button>
                    <button class="ajax_update">ajax更新</button>
    
                </td>
                <td>
                    <button><a href="/del_class/?id={{ item.id }}" class="delete">删除</a></button>
    {#                <button class="ajax_delete">ajax删除</button>#}
                </td>
            </tr>
        {% endfor %}
    
        </tbody>
    </table>
    <br><br>
    <button><a href="/add_class/" target="_blank">添加班级</a></button>
    <button id="ajax_add">ajax添加班级</button>
    </div>
    </body>
    </html>
    
    # add_class.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>增加班级</title>
        <style>
            a {
                color: black;
                text-decoration: none;
            }
        </style>
    </head>
    <body>
    <h2>增加班级</h2>
    <form action="/add_class/" method="post">
        班级名称:<input type="text" name="classname">
        <input type="submit" value="提交">
        <button><a href="/classes/">取消</a></button>
        <br><span style="color:red; font-size: 12px;">{{ data }}</span>
    </form>
    </body>
    </html>
    
    # update_class.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>班级更新</title>
        <style>
            a {
                color: black;
                text-decoration: none;
            }
        </style>
    </head>
    <body>
    <h2>更新班级名字</h2>
    <form action="/update_class/" method="post">
        <input type="hidden" name="id" value="{{ id }}">
        班级名称:<input type="text" name="classname" value="{{ cname }}">
        <input type="submit" value="更新">
        <button><a href="/classes/">取消</a></button>
        <br><span style="color: red; font-size: 12px">{{ data }}</span>
    </form>
    </body>
    </html>
    
    # urls.py
    
    # 获取班级信息
    @deco
    def classes(request):
        sql = 'select * from classes order by id'
        classes = mysql(sql)[0]
        return render(request, 'classes.html', {'classes': classes})
    
    # 添加班级
    @deco
    def add_class(request):
        if request.method == 'GET':
            return render(request, 'add_class.html')
        else:
            classname = request.POST.get('classname')
    
            if not classname:
                data = '班级名称不能为空'
                return render(request, 'add_class.html', {'data': data})
    
            sql = "select * from classes where cname=%s"
            res = mysql(sql, (classname,))[0]
            if res:
                data = '班级名称已存在'
                return render(request, 'add_class.html', {'data': data})
    
            sql = 'insert into classes(cname) values(%s)'
            res = mysql(sql, (classname,))[1]
            # print(res)
    
            if res:
                return redirect('/classes/')
            else:
                return render(request, 'add_class.html')
    
    # 删除班级
    @deco
    def del_class(request):
        id = request.GET.get('id')
    
        sql = 'delete from students where cid=%s'
        res = mysql(sql, (id,))
    
        sql = 'delete from classes where id = %s'
        res = mysql(sql, (id,))
    
        return redirect('/classes/')
        # return HttpResponse('ok')
    
    # 更新班级
    @deco
    def update_class(request):
        if request.method == "GET":
            id = request.GET.get('id')
            # print(id)
            sql = "select * from classes where id = %s"
            classinfo = mysql(sql, (id,))[0]
            # print(classname)
            return render(request, 'update_class.html', classinfo)
            # return render(request,'update_class.html',{'classinfo': classinfo})
        else:
            id = request.POST.get('id')
            classname = request.POST.get('classname')
    
            # print(id, classname, 2222)
    
            if classname:
    
                sql = 'select * from classes where cname=%s'
                res = mysql(sql,(classname,))[0]
    
                if res:
                    data = '班级名称已存在'
                    return render(request, 'update_class.html', {'data': data})
    
                sql = "update classes set cname=%s where id=%s"
                res = mysql(sql, (classname, id))[1]
    
                return redirect('/classes/')
            else:
                data = '班级名称不能为空'
                return render(request, 'update_class.html', {'data': data})
    

    ajax增加和更新

    # classes.html
    
    <!--直接加在classes.html页面里面-->
    {# 遮罩层 #}
    <div class="shadow"></div>
    
    {# 弹出框层 #}
    <div class="add_model">
        {#    <input type="hidden" name="class_id">#}
        <div class="model">
            班级名称:<input type="text" name="classname" id="add_class">
            <button id="add">提交</button>
            <button class="add_cancel">取消</button>
            <br><span id="error" style="color:red; font-size: 12px;"></span>
        </div>
    </div>
    
    <div class="update_model">
        <div class="model">
            <input type="hidden" name="id" id="up_id">
            新的班级名称:<input type="text" name="classname" id="up_name">
            <button id="update">提交</button>
            <button class="up_cancel">取消</button>
            <br><span id="up_error" style="color:red; font-size: 12px;"></span>
        </div>
    
    {# 导入jQuery #}
    <script src="/static/js/jquery-1.12.4.min.js"></script>
    
    {# 删除 #}
    <script>
        $('.delete').click(function () {
            res = window.confirm('是否删除班级');
            return res;
         });
    </script>
    
    {#增加#}
    <script>
        $('#ajax_add').click(function () {
            $('.shadow, .add_model').css('display', 'block');
        });
    
        $('.add_cancel').click(function () {
            $('.shadow, .add_model').hide();
            window.location.href = '/classes/';
        });
    
        $('#add').click(function () {
            var classname = $('#add_class').val();
            $.ajax({
                type: 'POST',
                url: '/ajax_add_class/',
                data: {'classname': classname},
                success: function (data) {
                    var res = JSON.parse(data);
    
                    if (res['code'] == 10000) {
                        alert(res['msg']);
                        window.location.href = '/classes/';
                    } else {
                        $('#error').text(res['msg']);
                    }
                }
            })
        });
    
    </script>
    
    {#更新#}
    <script>
        $('.ajax_update').click(function () {
            $('.shadow, .update_model').show();
            var info = $(this).parent().prevAll();
            var classname = info[0].innerText;
            var id = info[1].innerText;
    
            $('#up_name').val(classname);
            $('#up_id').val(id)
        });
    
        $('.up_cancel').click(function () {
            $('.shadow, .update_model').hide();
            window.location.href = '/classes/';
        });
    
        $('#update').click(function () {
            var classname = $('#up_name').val();
            var id = $('#up_id').val();
            console.log(classname,id);
    
            $.ajax({
                type: 'POST',
                url: '/ajax_update_class/',
                data: {'classname': classname, 'id': id},
                success: function (data) {
                    var res = JSON.parse(data);
    
                    if (res['code'] == 10000) {
                        alert(res['msg']);
                        window.location.href = '/classes/';
                    } else {
                        $('#up_error').text(res['msg']);
                    }
                }
            })
        });
    
    </script>
    
    # urls.py
    
    # ajax添加
    @deco
    def ajax_add_class(request):
        classname = request.POST.get('classname')
    
        # 以json格式进行文件传输
        res = {'code': None, 'msg': None}
        if not classname:
            res['code'] = 10001
            res['msg'] = '班级名字不能为空'
            return HttpResponse(json.dumps(res))
    
        sql = 'select * from classes where cname=%s'
        resp = mysql(sql, (classname,))[0]
    
        if resp:
            res['code'] = 10001
            res['msg'] = f'班级--{classname}--已存在'
            return HttpResponse(json.dumps(res))
    
        sql = "insert into classes(cname) values(%s)"
        resp = mysql(sql, (classname,))[1]
        res['code'] = 10000
        res['msg'] = f'班级--{classname}--添加成功'
        return HttpResponse(json.dumps(res))
    
    # ajax更新
    @deco
    def ajax_update_class(request):
        classname = request.POST.get('classname')
        id = request.POST.get('id')
    
        res = {'code': None, 'msg': None}
        if not classname:
            res['code'] = 10001
            res['msg'] = '班级名字不能为空'
            return HttpResponse(json.dumps(res))
    
        sql = 'select * from classes where cname=%s'
        resp = mysql(sql, (classname,))[0]
    
        if resp:
            res['code'] = 10001
            res['msg'] = f'班级--{classname}--已存在'
            return HttpResponse(json.dumps(res))
    
        print(res)
        sql = "update classes set cname=%s where id=%s"
        resp = mysql(sql, (classname, id))[1]
        res['code'] = 10000
        res['msg'] = f'班级--{classname}--更新成功'
        print(res)
        return HttpResponse(json.dumps(res))
    
  • 相关阅读:
    SpringMvc 框架
    面试:你最大的长处和弱点分别是什么?这些长处和弱点对你在企业的业绩会有什么样的影响?
    线程、并发、并行、进程是什么,以及如何开启新的线程?
    面向对象三大特性
    一台客户端有三百个客户与三百个客户端有三百个客户对服务器施压,有什么区别?
    JavaScript 引擎
    Spring Data JPA简介 Spring Data JPA特点
    redo log 有什么作用?
    Spring的简介和优点?
    学习笔记——享元模式Flyweight
  • 原文地址:https://www.cnblogs.com/Hades123/p/11366107.html
Copyright © 2020-2023  润新知