s4 示例要点

    # 模态框编辑(单表)
    
        import json
        def modal_edit_class(request):
            ret={'status':True,'message':None}
            try:
                nid =request.POST.get('nid')
                content = request.POST.get('content')
                sqlhelper.modify('update class set title=%s where id= %s',[content,nid,])
            except Exception as e:
                ret['status']=False
                ret['message']='something wrong!'
                # ret['message']=str(e)
            return HttpResponse(json.dumps(ret))

    
        onclick="modelEdit(this);"
        function modelEdit(ths){
            document.getElementById('shadow').classList.remove('hide');
            document.getElementById('editmodal').classList.remove('hide');
            var row=$(ths).parent().prevAll();
            var content=$(row[0]).text();
            $('#edittitle').val(content);

            var contentid=$(row[1]).text();
            $('#editid').val(contentid)
        }

        function editAjaxSend(){
            var nid=$('#editid').val();
            var content=$('#edittitle').val();
            $.ajax({
                url:'/modal_edit_class/',
                type:'POST',
                data:{'nid':nid,'content':content},
                success:function(arg){
                    arg=JSON.parse(arg);
                    if(arg.status){
                        location.reload()
                    }else{
                        alert(arg.message)
                    }
                }
            })
        }

    # 模态框style
    
        <style>
             .hide{
                 display:none;
             }
            .shadow{
                position: fixed;
                left:0;
                right:0;
                bottom:0;
                top:0;
                background-color: black;
                opacity: 0.4;
                z-index: 999;
            }
             .add_modal{
                  position: fixed;
                left:50%;
                top:50%;
                 width:400px;
                 height:300px;
                 background-color: white;
                 z-index: 1000;
                 margin-left: -200px;
                 margin-top: -200px;
             }

        </style>

    # 模态框编辑(一对多)


        <div id='shadow'class="shadow hide"></div>
        <div  id='addmodel'class="add_modal hide">
            <p>
                姓名<input id="addname" type="text"name="name"placeholder="姓名">
            </p>
            <p>
               班级
                <select id="addclassid" name="classid">
                    {% for row in class_list %}
                        <option value="{{ row.id }}">{{ row.title }}</option>
                    {% endfor %}
                </select>
            </p>
            <input  id='btnadd' type="button" value="添加"/>
            <span id="adderror"style="color: red"></span>
        </div>

        <div  id='editmodel'class="add_modal hide">
            <h3>编辑学生信息</h3>
            <p>
                姓名<input id="editname" type="text"name="name"placeholder="姓名">
                <input type="text"id="editid"style="display: none">
            </p>
            <p>
               班级
                <select id="editclassid" name="classid">
                    {% for row in class_list %}
                        <option value="{{ row.id }}">{{ row.title }}</option>
                    {% endfor %}
                </select>
            </p>
            <input  id='btnedit' type="button" value="更新"/>
            <span id="editerror"style="color: red"></span>
        </div>


        <script src="/static/jquery-1.12.4.js"></script>
        <script>
            $(function(){
                $('#addmodel').click(function(){
                    $('#shadow,#addmodel').removeClass('hide')
                });
                $('#btnadd').click(function(){
                    $.ajax({
                        url:"/modal_add_student/",
                        type:'POST',
                        data:{'name':$('#addname').val(),'class_id':$('#addclassid').val()},
                        success:function(arg){
                            arg=JSON.parse(arg);
                            if(arg.status){
                                location.reload()
                            }else{
                                $('#adderror').text(arg.message)
                            }
                        }
                    })
                });

                $('.btn_edit').click(function(){
                    $('#shadow,#editmodel').removeClass('hide');
                    var tds=$(this).parent().prevAll();
                    var studentid=$(tds[2]).text();
                    var studentname=$(tds[1]).text();
                    var classid=$(tds[0]).attr('clsid');
                    $('#editid').val(studentid);
                    $('#editname').val(studentname);
                    $('#editclassid').val(classid)
                });

                $('#btnedit').click(function(){
                    $.ajax({
                        url:'/modal_edit_student/',
                        type:'POST',
                        data:{'nid':$('#editid').val(),'name':$('#editname').val(),'class_id':$('#editclassid').val()},
                        dataType:'JSON',
                        success:function(arg){
                            if(arg.status){
                                location.reload()
                            }else{
                                $('#editerror').text(arg.message)
                            }
                        }
                    })
                })
            })
        </script>

    # 多对多数据查看、ULR添加、编辑,ajax添加
        
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                .hide{
                    display: none;
                }
                .shadow{
                    /*相对于窗口*/
                    position: fixed;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    top: 0;
                    
                    opacity: 0.4;
                    z-index: 999;
                }
                .loading{
                    position: fixed;
                    width: 32px;
                    height: 32px;
                    left: 50%;
                    top:50%;
                    margin-left: -16px;
                    margin-top: -16px;
                    background-image: url("/static/images/loading.gif");

                }
                .add-modal{
                    position: fixed;
                    top: 50%;
                    left: 50%;
                    width: 400px;
                    height: 300px;
                    z-index: 1000;
                    background-color: white;
                    margin-left: -200px;
                    margin-top: -200px;
                }
            </style>
        </head>
        <body>
            <h1>老师列表</h1>
            <a href="/add_teacher/">添加</a>
            <a id="btnAdd">对话框添加</a>
            <table border="1">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>老师姓名</th>
                        <th>任教班级</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for row in teacher_list %}
                        <tr>
                            <td>{{ row.tid }}</td>
                            <td>{{ row.name }}</td>
                            <td>
                                {% for item in row.titles %}
                                    <span style="display: inline-block;padding: 5px; border: 1px solid red;">{{ item }}</span>
                                {% endfor %}

                            </td>
                            <td>
                                <a href="/edit_teacher/?nid={{ row.tid }}">编辑</a>
                                |
                                <a>删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>

            <div id="shadow" class="shadow hide"></div>
            <div id="loading" class="loading hide"></div>
            <div id="addModal" class="add-modal hide">
                <p>
                    老师姓名:<input type="text" name="name" id="addName" />
                </p>
                <p>
                    <select id="classIds"  multiple size="10">

                    </select>
                </p>
                <a id="addSubmit">提交</a>
            </div>

            <script src="/static/jquery-1.12.4.js"></script>
            <script>
                $(function(){
                    bindAdd();
                    bindAddSubmit();
                });

                function bindAdd(){
                    $('#btnAdd').click(function(){
                        $('#shadow,#loading').removeClass('hide');
                        /*
                        发送ajax请求,获取所有班级信息
                        再classIds下拉框中生成option
                         */
                        $.ajax({
                            url:'/get_all_class/',
                            type:'GET',
                            dataType: 'JSON',
                            success:function(arg){
                                /*
                                arg = [
                                    {id:1,title:xx}
                                    {id:1,title:xx}
                                    {id:1,title:xx}
                                ]
                                */
                                //console.log(arg);
                                // 将所有的数据添加到select,option
                                $.each(arg,function(i,row){
                                    var tag = document.createElement('option');
                                    tag.innerHTML = row.title;
                                    tag.setAttribute('value',row.id);

                                    $('#classIds').append(tag);
                                });
                                $('#loading').addClass('hide');
                                $('#addModal').removeClass('hide');
                            }
                        })

                    })
                }

                function bindAddSubmit(){
                    $('#addSubmit').click(function(){
                        var name = $('#addName').val();
                        var class_id_list = $('#classIds').val();
                        console.log(name,class_id_list);
                        $.ajax({
                            url:'/modal_add_teacher/',
                            type: 'POST',
                            data: {'name':name, 'class_id_list': class_id_list},
                            dataType:'JSON',
                            traditional: true,// 如果提交的数据的值有列表,则需要添加此属性
                            success: function (arg) {
                                if(arg.status){
                                    location.reload();
                                }else{
                                    alert(arg.message);
                                }
                            }
                        })
                    });
                }
            </script>
        </body>
        
        # 多对多,以老师表展示
        def teachers(request):
            # teacher_list = sqlheper.get_list('select id,name from teacher',[])
            teacher_list = sqlheper.get_list("""
              select teacher.id as tid,teacher.name,class.title from teacher
                LEFT JOIN teacher2class on teacher.id = teacher2class.teacher_id
                left JOIN class on class.id = teacher2class.class_id;
            """,[])
            print(teacher_list)
            result = {}
            for row in teacher_list:
                tid =row['tid']
                if tid in result:
                    result[tid]['titles'].append(row['title'])
                else:
                    result[tid] = {'tid': row['tid'],'name':row['name'],'titles': [row['title'],]}


            return render(request,'teacher.html',{'teacher_list':result.values()})



        def test(request):
            return render(request,'test.html',{'k1': 1,'k2': 'uuu'})


        def add_teacher(request):
            if request.method == "GET":
                class_list = sqlheper.get_list('select id,title from class',[])
                return render(request,'add_teacher.html',{'class_list': class_list})
            else:
                name = request.POST.get('name')
                # 老师表中添加一条数据
                teacher_id = sqlheper.create('insert into teacher(name) values(%s)',[name,])
                # 老师和班级关系表中插入数据
                # ['3', '4', '5', '6', '7']
                # 获取当前添加的老师id=2
                # 23
                # 24
                #
                class_ids = request.POST.getlist('class_ids')
                # 多次连接,多次提交
                # for cls_id in class_ids:
                #     sqlheper.modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',[teacher_id,cls_id,])
                # 连接一次,多次提交
                # obj = sqlheper.SqlHelper()
                # for cls_id in class_ids:
                #     obj.modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',[teacher_id,cls_id,])
                # obj.close()
                # 一次连接,一次提交
                data_list = []
                for cls_id in class_ids:
                    temp = (teacher_id,cls_id,)
                    data_list.append(temp)
                obj = sqlheper.SqlHelper()
                obj.multiple_modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',data_list)
                obj.close()
                return redirect('/teachers/')


        def edit_teacher(request):
            if request.method == "GET":
                nid = request.GET.get('nid')
                obj = sqlheper.SqlHelper()
                teacher_info = obj.get_one('select id,name from teacher where id =%s',[nid,])
                class_id_list = obj.get_list('select class_id from teacher2class where teacher_id=%s',[nid,])
                class_list = obj.get_list('select id,title from class',[])
                obj.close()

                print('当前老师信息',teacher_info)
                print('当前老师任教的班级id',class_id_list)
                temp = []
                for i in class_id_list:
                    temp.append(i['class_id'])
                print('所有班级',class_list)
                # return HttpResponse('...')
                return render(request,'edit_teacher.html',{
                    'teacher_info': teacher_info,
                    'class_id_list': temp,
                    'class_list': class_list,
                })
            else:
                nid = request.GET.get('nid')
                name = request.POST.get('name')
                class_ids = request.POST.getlist('class_ids')
                obj = sqlheper.SqlHelper()
                # 更新老师表
                obj.modify('update teacher set name=%s where id=%s',[name,nid])
                # 更新老师和班级关系表
                # 先把当前老师和班级的对应关系删除,然后再添加
                obj.modify('delete from teacher2class where teacher_id=%s',[nid,])

                data_list = []
                for cls_id in class_ids:
                    temp = (nid,cls_id,)
                    data_list.append(temp)
                # map?lambda表达式?
                obj = sqlheper.SqlHelper()
                obj.multiple_modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',data_list)
                obj.close()

                return redirect('/teachers/')


        def get_all_class(request):
            obj = sqlheper.SqlHelper()
            class_list = obj.get_list('select id,title from class',[])
            obj.close()
            return HttpResponse(json.dumps(class_list))


        def modal_add_teacher(request):
            ret = {'status': True,'message': None}
            try:
                name = request.POST.get('name')
                class_id_list = request.POST.getlist('class_id_list')

                teacher_id = sqlheper.create('insert into teacher(name) values(%s)',[name,])

                data_list = []
                for cls_id in class_id_list:
                    temp = (teacher_id,cls_id,)
                    data_list.append(temp)
                obj = sqlheper.SqlHelper()
                obj.multiple_modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',data_list)
                obj.close()
            except Exception as e:
                ret['status'] = False
                ret['message'] = "处理失败"
            return HttpResponse(json.dumps(ret))
            
    # 后台管理布局示例
    
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                body{
                    margin: 0;
                }
                .left{
                    float: left;
                }
                .right{
                    float:right;
                }
                .hide{
                    display: none;
                }
                .pg-header{
                    height: 48px;
                    min-width: 1190px;
                    
                    line-height: 48px;
                }
                .pg-header .logo{
                    color:white;
                    font-size: 18px;
                    width: 200px;
                    text-align: center;
                    border-right:1px solid #5bc0de;
                }
                .pg-header .rmenus a{
                    display: inline-block;
                    padding: 0 15px;
                    color:white;
                }
                .pg-header .rmenus a:hover{
                    background-color: #5bc0de;
                }
                .pg-header .avatar{
                    padding: 0 20px;
                }
                .pg-header .avatar:hover .user{
                    display: block;
                }
                .pg-header .avatar img{
                    border-radius: 50%;
                }
                .pg-header .avatar .user{
                    position: absolute;
                    width:100px;
                    top:48px;
                    right:17px;
                    background-color: white;
                    border:1px solid #DDDDDD;
                    color: white;
                    z-index: 100;
                    display: none;
                }
                .pg-header .avatar .user a{
                    display: block;
                }
                .menus{
                    width: 200px;
                    position: absolute;
                    left: 0;
                    bottom: 0;  /* height: 500px; */
                    top:48px;
                    border-right: 1px solid #DDDDDD;
                    background-color: #EEEEEE;
                }
                .content{
                    position: absolute;
                    left: 200px;
                    right: 0;
                    top: 48px;
                    bottom: 0;
                    min-width: 990px;
                    overflow: scroll;   /*  右侧随内容增加 */
                    z-index: 99;
                }
                .pg-body .menus a{
                    display: block;
                    padding: 10px 5px;
                    border-bottom: 1px solid #FFFFFF;
                }
            </style>
        </head>
        <body>
            <div class="pg-header">
                <div class="logo left">XXX后台管理</div>
                <div class="avatar right" style="position: relative">
                    <img style="width: 40px;height: 40px" src="/static/images/1.jpg" alt="">
                    <div class="user">
                        <a href="">资料</a>
                        <a href="">注销</a>
                    </div>
                </div>
                <div class="rmenus right">
                    <a href="">消息</a>
                    <a href="">邮件</a>
                </div>
            </div>
            <div class="pg-body">
                <div class="menus">
                    <a href="">班级管理</a>
                    <a href="">学生管理</a>
                    <a href="">老师管理</a>
                </div>
                <div class="content">内容</div>
            </div>
        </body>
        </html>

posted @ 2020-01-18 21:07  badweather  阅读(86)  评论(0编辑  收藏  举报