• Django之学员管理二


    Django之学员管理二

      学生表的一对多的增删改查

    views.py

    def students(request):
        #select students.sid,students.name,classes.title from students left JOIN classes on students.classes_id=classes.nid;
        conn = pymysql.connect(host="127.0.0.1",port=3306,user='root',passwd='redhat',db='weibo',charset='utf8')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #改为字典
        cursor.execute("select students.sid,students.name,classes.title from students left JOIN classes on students.classes_id=classes.nid;")
        students_list = cursor.fetchall()
        print("students",students_list)
        cursor.close()
        conn.close()
        return render(request, "students.html", {"students_list": students_list})
    
    def add_students_add(request):
        if request.method=="GET":
            conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd='redhat', db='weibo', charset='utf8')
            cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 改为字典
            cursor.execute("select nid,title from classes")
            class_list = cursor.fetchall()
            print("classes", class_list)
            cursor.close()
            conn.close()
            return render(request,"add_students.html",{"class_list":class_list})
        else:
            htminput_name = request.POST.get("name")
            classes_id = request.POST.get("classes_id")
            conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd='redhat', db='weibo', charset='utf8')
            cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 改为字典
            cursor.execute("insert into students(name,classes_id) value(%s,%s)",[htminput_name,classes_id])
            conn.commit()
            cursor.close()
            conn.close()
            return redirect("/students/")
    
    def del_students_del(request):
        sid = request.GET.get("sid")
        conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd='redhat', db='weibo', charset='utf8')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 改为字典
        cursor.execute("delete from students where sid=%s",[sid,])
        conn.commit()
        cursor.close()
        conn.close()
        return redirect("/students/")
    
    from utils import sqlheper
    def edit_students_edit(request):
        if request.method == "GET":
            sid = request.GET.get("sid")
            class_list = sqlheper.get_list("select * from classes",[])
            students_name = sqlheper.get_one("select sid,name,classes_id from students where sid=%s",[sid,])
            return render(request,"edit_students.html",{"class_list":class_list,"students_name":students_name})
        else:
            sid = request.GET.get("sid")
            name = request.POST.get("name")
            classes_id = request.POST.get("classes_id")
            sqlheper.modify("update students set name=%s,classes_id=%s where sid=%s",[name,classes_id,sid])
            return redirect("/students/")
    

      

    sqlheper.py

    import pymysql
    
    def get_list(sql,args):
        """
        获取列表信息
        :param sql:
        :param args:
        :return:
        """
        conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd='redhat', db='weibo', charset='utf8')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 改为字典
        cursor.execute(sql,args)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result
    
    def get_one(sql,args):
        """
        获取一条数据信息
        :param sql:
        :param args:
        :return:
        """
        conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd='redhat', db='weibo', charset='utf8')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 改为字典
        cursor.execute(sql, args)
        result = cursor.fetchone()
        cursor.close()
        conn.close()
        return result
    
    def modify(sql,args):
        """
        提交事务,以便执行增删改操作
        :param sql: 
        :param args: 
        :return: 
        """
        conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd='redhat', db='weibo', charset='utf8')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 改为字典
        cursor.execute(sql,args)
        conn.commit()
        cursor.close()
        conn.close()
    

      

    students.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>学生列表</h1>
        <div>
            <a href="/add_students_add/">添加学生</a>
        </div>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>学生姓名</th>
                    <th>所属班级</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for students in students_list %}
                    <tr>
                        <td>{{ students.sid }}</td>
                        <td>{{ students.name }}</td>
                        <td>{{ students.title }}</td>
                        <td>
                            <a href="/del_students_del/?sid={{ students.sid }}">删除</a>
                            |
                            <a href="/edit_students_edit/?sid={{ students.sid }}">编辑</a>
                        </td>
                    </tr>
                {% endfor %}
    
            </tbody>
        </table>
    </body>
    </html>
    

      

    add_students_add.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>添加学生</h1>
        <form method="post" action="/add_students_add/">
            <p>学生姓名:<input type="text" name="name" placeholder="please input your name"></p>
            <p>所属班级:
                <select name="classes_id">
                    {% for foo in class_list %}
                        <option value="{{ foo.nid }}">{{ foo.title }}</option>
                    {% endfor %}
                </select>
            </p>
            <input type="submit" value="submit" >
        </form>
    </body>
    </html>
    

      

    edit_studetns_edit.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>编辑学生</h1>
        <form method="post" action="/edit_students_edit/?sid={{ students_name.sid }}">
            <p>学生姓名:<input type="text" name="name" value="{{ students_name.name }}"></p>
            <p>学生班级:
                <select name="classes_id">
                    {% for row in class_list %}
                        {% if row.nid == students_name.classes_id %}
                            <option selected value="{{ row.nid }}">{{ row.title }}</option>
                        {% else %}
                            <option value="{{ row.nid }}">{{ row.title }}</option>
                        {% endif %}
                    {% endfor %}
                </select>
            </p>
            <input type="submit" value="submit">
        </form>
    
    </body>
    </html>
    

      

    模态对话框添加班级classes:

      模态对话框就是在页面上做两层处理。第一层是遮罩层,第二层是呈现对话框的显示层

      对话框的处理在页面的头《head》里要写样式:

    classes.html

    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .hide{
                display: none;
            }
            .shadow{
                position: fixed;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                background-color: black;
                opacity: 0.4;
                z-index: 999;
            }
            .model{
                z-index: 1000;
                position: fixed;
                left: 50%;
                top: 50%;
                height: 300px;
                 400px;
                background-color: white;
                margin-left: -200px;
                margin-top: -150px;
            }
        </style>
    </head>
    

      在《body》里是:

        <div id="shadow" class="shadow "></div>
        <div id="model" class="model ">
            <form method="post" action="/model_ajax_classes_add/">
                <p>添加班级:<input type="text" name="title"></p>
                <input type="submit" value="submit">{{ msg }}
            </form>
        </div>
        <script>
            function showModal(){
                document.getElementById("shadow").classList.remove("hide");
                document.getElementById("model").classList.remove("hide");
            }
        </script>
    </body>
    </html>
    

      

      在模态对话框里,用到的form提交方式,期特点是提交页面就刷新。其弊病是在提交数据错误时。也依旧刷新,而不是在当前页面显示错误值。

      比如,在输入空班级时,后端判断不得为0时,form依旧刷新,并没有提示词。

      Form表单的特性就是刷新

        在form表单中,使用form表单,在正常提交跳转是没有问题的,但是bug在于错误提交数据,页面还是会刷新,而不是在原有的页面中反馈错误信息。

        所以,这里就需要用到Ajax操作。

      另建对应单独的执行函数:

    views.py

    def model_ajax_classes_add(request):
        model_ajax_add_classes_title = request.POST.get("title")
        if len(model_ajax_add_classes_title)>0:
            sqlheper.modify("insert into classes(title) values(%s)",[model_ajax_add_classes_title,])
            return redirect("/classes/")
        else:
            return render(request,"classes.html",{"msg":"班级名称不能为空"})
    

      

    Ajax对话框提交班级信息的实现方式:

      Ajax的特点和知识点:

        特点:Ajax提交,页面不刷新,形象理解为偷偷的提交数据给后端处理

           实现ajax方法,要使用jQuery

        知识点:1、ajax以什么方式提交数据type。

            2、ajax往哪里提交要指定url。

            3、ajax提交什么数据要指定data。

            4、ajax提交成功和失败分别要干什么。

              1-3执行完,会等待。

              data是提交的数据,是字典的类型,values值提交的url中,data{"key":().val()}   val是标定id里输入的值

             success:function(data) 当服务端处理完函数返回数据时,自动调用这个function函数,这里的data是服务端返回的值.

              比如:console.log(data)

     在ajax执行完需要跳转时,是不能自行跳转的,需要些js来实现跳转。在django里用redirect也是实现不了的。

        js的实现就是用location.href = "/url/"

      ajax的执行流程,触发ajax,作为服务端的ajax获取到前端传输的数据data,以字典的value值的形式传给后端服务,当后端收到数据后,给前端一个返回值,执行success的function函数返回前端应该收到的返回值。在前端代码的console里可看到

     ajax的班级添加demo示例:

    classes.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>classes</title>
        <style>
            .hide{
                display: none;
            }
            .shadow{
                position: fixed;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                background-color: black;
                opacity: 0.4;
                z-index: 999;
            }
            .modal{
                z-index: 1000;
                position: fixed;
                left: 50%;
                top: 50%;
                height: 300px;
                 400px;
                background-color: white;
                margin-left: -200px;
                margin-top: -150px;
            }
        </style>
    </head>
    <body>
        <h1>classes_list</h1>
        <div>
            <a href="/add_class/">添加</a>
            |
            <a onclick="showModal();">对话框添加</a>
            |
            <a>对话框</a>
        </div>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>班级名称</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for item in class_lsit %}
                    <tr>
                        <td>{{ item.nid }}</td>
                        <td>{{ item.title }}</td>
                        <td>
                            <a href="/del_class/?nid={{ item.nid }}">删除</a>
                            |
                            <a onclick="modelEdit();">对话框编辑</a>
                            |
                            <a href="/edit_class/?nid={{ item.nid }}">编辑</a>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    
        <div id="shadow" class="shadow hide"></div>
        <div id="modal" class="modal hide">
            <p>添加班级:<input id="title" type="text" name="title" placeholder="班级名称"></p>
            <input type="button" value="submit" onclick="AjaxSend();"/>
            <input type="button" value="取消" onclick="cancleModal();"/><span id="errormsg"></span>
        </div>
    
        <script src="/static/jquery-1.12.4.js"></script>
        <script>
            function showModal() {
                document.getElementById("shadow").classList.remove("hide");   //找到遮罩层,并去挑遮罩层
                document.getElementById("modal").classList.remove("hide");
    
            }
    
            function cancleModal() {
                document.getElementById('shadow').classList.add('hide');
                document.getElementById('modal').classList.add('hide')
                document.getElementById('eidtModal').classList.add('hide')
            }
    
            function AjaxSend(){
                $.ajax({
                    url:'/modal_add_classes_ajax/',   //往哪里提交
                    type:'POST',                      //以什么方式提交
                    data:{"title":$("#title").val()},  //拿到全段输入的值
                    success:function (data) {
                        //当服务端处理完成后,返回数据时,该函数自动调用
                        //data是服务端返回的值
                        console.log(data);
                        if(data=="ok"){
                            location.href='/classes/'; //指定提交成功后跳转到哪里
                        }else {
                            $('#errormsg').text(data);
                        }
                    }
                })
            }
        </script>
    </body>
    </html>
    

      views.py的model_add_classes_ajax函数的操作示例:

    def modal_add_classes_ajax(request):
        #获取前端的title
        title = request.POST.get('title')
        print(title)
        if len(title) > 0:
            sqlheper.modify('insert into classes(title) values(%s)',[title,])
            return HttpResponse('ok')
        else:
            return HttpResponse('班级标题不能为空')
    

      

     --------- END ----------

       

  • 相关阅读:
    实验 3:Mininet 实验——测量路径的损耗率
    福州大学软件工程实践个人编程作业
    实验 2:Mininet 实验——拓扑的命令脚本生成
    初识MinIO
    基础《Go学习笔记》读书笔记——函数
    Linux配置Golang 依赖包安装
    《Linux shell 脚本攻略》第1章——读书笔记
    vscode连接云服务,搭建Python远程开发
    Python多线程
    Python多进程
  • 原文地址:https://www.cnblogs.com/george92/p/10930854.html
Copyright © 2020-2023  润新知