Django框架学习笔记(六)

本文介绍了一个基于Django框架的教师信息管理系统,实现了教师表的增删改查功能,并通过多对多关系关联班级表,支持教师授课班级的显示及多选添加。系统采用对话框式添加方式,利用Ajax进行数据交互,提高了用户体验。
摘要由CSDN通过智能技术生成

之前 的一篇中通过普通的方式实现了教师表的增删改查。由于教师表与班级表之间存在多对对的关系,因此在原来的基础上做了一些修改:

  • 通过访问localhost:8080/teachers/查看教师信息时,增加教师授课班级的显示
  • 添加教师时,支持多选【可以get到在Django中如何获取多个值】
  • 封装了一个SqlHelper类,通过对象的方式实现数据库的操作
  • 实现了对话框式的添加【ajax的使用】

后期继续完善对话框式的编辑以及通过ajax实现的删除

urls.py增加:

path('get_all_class/', views.get_all_class),
path('modal_add_teacher/', views.modal_add_teacher),

views.py增加:

def get_all_class(request):
    import time
    time.sleep(3)  # 等待时间会出现加载界面
    obj = sqlHelper.SqlHelper()
    class_list = obj.get_list("select * 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')
        obj = sqlHelper.SqlHelper()
        last_id = obj.create("insert into teacher(name) values(%s)", [name, ])
        data_list = []
        for item in class_id_list:
            temp = (last_id, item)
            data_list.append(temp)
        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'] = str(e)
    return HttpResponse(json.dumps(ret))

views.py修改:

def teachers(request):
    teacher_list = sqlHelper.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
    """, [])
    result = {}
    for teacher_item in teacher_list:
        tid = teacher_item['tid']
        if tid in result:
            result[tid]['titles'].append(teacher_item['title'])
        else:
            result[tid] = {'tid': teacher_item['tid'],
                           'name': teacher_item['name'],
                           'titles': [teacher_item['title'], ]}
    return render(request, 'teachers.html', {'teacher_list': result.values()})

def edit_teacher(request):
    if request.method == 'GET':
        teacher_id = request.GET.get('tid')
        obj = sqlHelper.SqlHelper()
        # 当前老师信息
        teacher_info = obj.get_one("select * from teacher where id=%s", [teacher_id])
        # 老师任教班级id [{'class_id':..},{'class_id':..}]
        class_id_list = obj.get_list("select class_id from teacher2class where teacher_id=%s", [teacher_id])
        temp = []
        for item in class_id_list:
            temp.append(item['class_id'])
        # 班级列表
        class_list = obj.get_list("select * from class", [])
        obj.close()
        return render(request, 'edit_teacher.html', {'teacher_info': teacher_info,
                                                     'class_id_list': temp,
                                                     'class_list': class_list})
    else:
        teacher_id = request.POST.get('id')
        teacher_name = request.POST.get('name')
        class_ids = request.POST.getlist('class_ids')
        data_list = []
        for class_id in class_ids:
            temp = (teacher_id, class_id)
            data_list.append(temp)

        obj = sqlHelper.SqlHelper()
        obj.modify("update teacher set name=%s where id=%s",
                   [teacher_name, teacher_id])
        obj.modify("delete from teacher2class where teacher_id=%s", [teacher_id])
        obj.multiple_modify("insert into teacher2class(teacher_id,class_id) "
                            "values(%s, %s)", data_list)
        obj.close()
        return redirect('/teachers/')

teachers.tml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>教师列表</title>
    <style type="text/css">
        .hide{display: none;}
        .shadow{
            position: fixed;
            left:0;
            right: 0;
            top: 0;
            bottom: 0;
            background-color: rgba(0,0,0,0.4);
            z-index: 9999;
        }
        .loading{
            position: fixed;
            width:260px;
            height:400px;
            top:50%;
            left: 50%;
            margin-left:-130px;
            margin-top:-200px;
            background-image:url("/static/images/loading.gif");
        }
        .modal{
            z-index: 10000;
            position: fixed;
            left: 50%;
            top: 50%;
            width: 400px;
            height: 300px;
            background-color: #fff;
            margin-left: -200px;
            margin-top: -150px;
        }
    </style>
</head>
<body>
<h1>教师列表</h1>
<div>
    <a href="/add_teacher/">添加教师</a>
    |
    <a id="btnAdd">对话框添加教师</a>
</div>
<table border="1">
    <thead>
    <tr>
        <th>教师ID</th>
        <th>教师名称</th>
        <th>任教班级名称</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    {% for teacher_item in teacher_list %}
        <tr>
            <td>{{ teacher_item.tid }}</td>
            <td>{{ teacher_item.name }}</td>
            <td>
                {% for title in teacher_item.titles %}
                    <span>{{ title }}</span>
                {% endfor %}
            </td>
            <td>
                <a href="/edit_teacher/?tid={{ teacher_item.tid }}">编辑</a>|
                <a href="/del_teacher/?tid={{ teacher_item.tid }}">删除</a>
            </td>
        </tr>
    {% endfor %}
    </tbody>
</table>
<div id="shadow" class="shadow hide"></div>
<div id="loading" class="loading hide"></div>
<div id="add-modal" class="modal hide">
    <h1>添加教师</h1>
    教师名称:<input type="text" id="teacher_name" name="teacher_name"/><br/>
    任教班级:
    <select name="" id="classIds" multiple size="5"></select>
    <a id="addSubmit">提交</a>
</div>
<script type="text/javascript" src="/static/js/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
    $(function(){
        bindAdd();
        bindAddSubmit();

    });

    function bindAdd(){
        $("#btnAdd").click(function () {
            $("#shadow,#loading").removeClass('hide');
            /**
             * 1.发送ajax请求,获取所有的班级信息
             * 2.在select下生成所有的option
             */
            $.ajax({
                url:'/get_all_class/',
                type:'post',
                dataType:'JSON',
                success:function(data){
                    console.log(data);
                    //将所有数据添加到select,option
                    $.each(data, function (i, row) {
                        let tag = document.createElement('option');
                        tag.innerHTML = row.title;
                        tag.setAttribute('value', row.id);
                        $("#classIds").append(tag);
                    });
                    $("#loading").addClass('hide');
                    $("#add-modal").removeClass("hide");
                }
            })
        })
    }

    function bindAddSubmit(){
        $("#addSubmit").click(function(){
            let name = $("#teacher_name").val();
            let class_id_list = $("#classIds").val();
            $.ajax({
                url:'/modal_add_teacher/',
                type:'post',
                data:{'name':name, 'class_id_list': class_id_list},
                traditional:true,//如果提交的数据有列表,则需要添加此属性
                dataType:'JSON',
                success:function(data){
                    if(data.status){
                        location.reload();
                    }else{
                        alert(data.message);
                    }
                }
            })
        });
    }
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值