Django框架学习笔记(五)

这篇博客主要介绍了在Django框架下,如何实现学生表的增、删、改、查操作,特别是编辑时如何在select中默认显示当前班级。
摘要由CSDN通过智能技术生成

上一篇 完成了班级表的对话框操作。
这篇主要是学生表的对话框形式的操作:增、删、改、查

需要注意的是进行编辑操作时,select中如何默认显示当前所在的班级

urls.py中增加:

path('modal_add_student/', views.modal_add_student),
path('modal_edit_student/', views.modal_edit_student),
path('modal_del_student/', views.modal_del_student),

views.py中增加:

def modal_add_student(request):
    ret = {'status': True, 'message': None}
    try:
        name = request.POST.get('name')
        class_id = request.POST.get('class_id')
        sqlHelper.modify("insert into student(name, class_id) values(%s, %s)",
                         [name, class_id])
    except Exception as e:
        ret['status'] = False
        ret['message'] = str(e)
    return HttpResponse(json.dumps(ret))


def modal_edit_student(request):
    ret = {'status': True, 'message': None}
    try:
        sid = request.POST.get("id")
        name = request.POST.get("name")
        class_id = request.POST.get("class_id")
        sqlHelper.modify("update student set name=%s,class_id=%s where id=%s",
                         [name, class_id, sid])
    except Exception as e:
        ret['status'] = False
        ret['message'] = str(e)
    return HttpResponse(json.dumps(ret))


def modal_del_student(request):
    ret = {'status': True, 'message': None}
    try:
        sid = request.POST.get("sid")
        sqlHelper.modify("delete from student where id=%s", [sid])
    except Exception as e:
        ret['status'] = False
        ret['message'] = str(e)
    return HttpResponse(json.dumps(ret))

students.html修改为:

<!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;
        }
        .add-modal,.edit-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_student/">添加学生</a>
    <a href="#" id="addModal">模态框添加学生</a>
</div>
<table border="1">
    <thead>
    <tr>
        <th>学生ID</th>
        <th>学生姓名</th>
        <th>所属班级</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    {% for student_item in student_list %}
        <tr>
            <td>{{ student_item.id }}</td>
            <td>{{ student_item.name }}</td>
            <td classId="{{ student_item.class_id }}">{{ student_item.title }}</td>
            <td>
                <a href="/edit_student/?sid={{ student_item.id }}">编辑</a>
                <a class="btn-edit">对话框编辑</a>
                |
                <a href="/del_student/?sid={{ student_item.id }}">删除</a>
                <a id="ajaxDel">ajax删除</a>
            </td>
        </tr>
    {% endfor %}
    </tbody>
</table>
<div id="shadow" class="shadow hide"></div>
<div id="add-modal" class="add-modal hide">
    <h2>添加学生</h2>
    <p>姓名:<input id="addName" type="text"/></p>
    <p>班级:<select name="classId" id="addClassId">
        {% for class_item in class_list %}
            <option value="{{ class_item.id }}">{{ class_item.title }}</option>
        {% endfor %}
    </select>
    </p>
    <p><input id="btnAdd" type="button" value="添加"></p>
    <span id="addErrorMsg"></span>
</div>
<div id="edit-modal" class="edit-modal hide">
    <h2>编辑学生</h2>
    <p>姓名:<input id="editName"  type="text"/></p>
    <input type="text" id="editId" name="studentId" hidden/>
    <p>班级:<select name="classId" id="editClassId">
        {% for class_item in class_list %}
            <option value="{{ class_item.id }}">{{ class_item.title }}</option>
        {% endfor %}
    </select>
    </p>
    <p><input id="btnEdit" type="button" value="更新"></p>
    <span id="editErrorMsg"></span>
</div>
<script type="text/javascript" src="/static/js/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("#addModal").click(function(){
            $("#shadow").removeClass("hide");
            $("#add-modal").removeClass("hide");
            return false; //阻止默认事件的发生
        });

        $("#btnAdd").click(function(){
            $.ajax({
                url:'/modal_add_student/',
                type:'post',
                data:{'name':$("#addName").val(), 'class_id':$("#addClassId").val()},
                success:function (data) {
                    data = JSON.parse(data);
                    if(data.status){
                        location.reload();
                    }else{
                        $("#addErrorMsg").text(data.message);
                    }
                }
            });
        });

        $(".btn-edit").click(function () {
            $("#shadow,#edit-modal").removeClass("hide");
            /**
             * 1.获取当前标签
             */
            let tds = $(this).parent().prevAll();
            let student_id = $(tds[2]).text();
            let student_name = $(tds[1]).text();
            let class_id = $(tds[0]).attr('classId');
            console.log(student_id,student_name, class_id);

            $("#editId").val(student_id);
            $("#editName").val(student_name);
            $("#editClassId").val(class_id);
        });

        $("#btnEdit").click(function(){
            $.ajax({
                url:'/modal_edit_student/',
                type:'post',
                data:{"id":$("#editId").val(),
                      "name":$("#editName").val(),
                      "class_id":$("#editClassId").val()},
                dataType:'JSON',
                success:function(data){
                    {#data = JSON.parse(data);#}
                    if(data.status){
                        location.reload();
                    }else{
                        $("#editErrorMsg").text(data.message);
                    }
                }
            })
        });

        $("#ajaxDel").click(function(){
            let del_id = $($(this).parent().prevAll()[2]).text();
            $.ajax({
                url:'/modal_del_student/',
                type:'post',
                data:{'sid': del_id},
                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、付费专栏及课程。

余额充值