Django--多对多表操作/通过母版渲染页面

Django--多对多表操作+母版

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

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

需求

  1. 对老师表进行增删改查,此时老师表和班级表是多对多关系

步骤

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

添加路由映射关系

urlpatterns = [
    # 新url方式
    url(r'^teachers/', teachers),
    url(r'^add_teacher/', add_teacher),
    url(r'^del_teacher/', del_teacher),
    url(r'^update_teacher/', update_teacher),
    # ajax方式
    url(r'^ajax_add_teacher/', ajax_add_teacher),
    url(r'^ajax_update_teacher/', ajax_update_teacher),
]

老师表的增删改查

# students.html -- 通过继承layout.html页面

{% extends 'layout.html' %}

{% block mycss %}
    <style>
        select {
            height: 34px;
            width: 203px;
            padding: 6px 12px;
            border: 1px solid #ccc;
            border-radius: 4px;
            background-color: #fff;
        }
    </style>
{% endblock %}

{% block mycontent %}
    <h3>学生表</h3>
    <table class="table table-hover table-bordered">
        <tbody>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>班级</th>
            <th>更新</th>
            <th>删除</th>
        </tr>
        {% for stu in students %}
            <tr>
                <td>{{ stu.sid }}</td>
                <td>{{ stu.name }}</td>
                <td>{{ stu.age }}</td>
                <td clsid="{{ stu.cid }}">{{ stu.cname }}</td>
                <td>
                    <button class="btn btn-info"><a href="/update_student/?id={{ stu.sid }}"
                                                    style="color: white;text-decoration: none;">更新</a></button>
                    <button class="ajax_update btn btn-primary">ajax更新</button>
                </td>
                <td>
                    <button class="btn btn-danger"><a href="/del_student/?id={{ stu.sid }}" class="delete"
                                                      style="color: white;text-decoration: none;">删除</a></button>
                    {#                <button class="ajax_delete">ajax删除</button>#}
                </td>
            </tr>
        {% endfor %}

        </tbody>
    </table>
    <br><br>
    <button class="btn btn-info"><a href="/add_student/" style="color: white;text-decoration: none;">添加学生</a></button>
    <button id="ajax_add" class="btn btn-primary">ajax添加学生</button>

    {# 遮罩层 #}
    <div class="shadow"></div>

    {# 弹出框层 #}
    {# 增加学生 #}
    <div class="add_model">
        {#    <input type="hidden" name="class_id">#}
        <div>
            <h4 style="text-align: center; margin-top: 20px;">增加学生</h4>
            <hr>
        </div>
        <div class="model" style="margin-left: 120px">
            名字:<input type="text" name="name" id="add_student"><br>
            年龄:<input type="text" name="age" id="add_age"><br>
            <div style="margin-top: 2px;margin-bottom: 2px">
                班级:<select name="add_cid" id="add_cid">
                {% for class in classes %}
                    <option value="{{ class.id }}">{{ class.cname }}</option>
                {% endfor %}
            </select></div>
            <span id="add_error" style="color:red; font-size: 12px; margin-bottom: 10px;"></span><br>
            <button id="add" class="btn btn-danger" style="margin-left: 48px;">添加</button>
            <button class="add_cancel btn btn-primary" style="margin-left: 40px;">取消</button>
        </div>
    </div>

    {# 更新学生 #}
    <div class="update_model">
        <div>
            <h4 style="text-align: center; margin-top: 20px;">更新学生</h4>
            <hr>
        </div>
        <div class="model" style="margin-left: 120px">
            <input type="hidden" name="sid" id="up_sid">
            姓名:<input type="text" name="name" id="up_name"><br>
            年龄:<input type="text" name="age" id="up_age">
            <div style="margin-top: 2px;margin-bottom: 2px">
                班级:<select name="up_cid" id="up_cid">
                {% for class in classes %}
                    <option value="{{ class.id }}">{{ class.cname }}</option>
                {% endfor %}
            </select>
            </div>
            <span id="up_error" style="color:red; font-size: 12px; margin-bottom: 10px;"></span><br>
            <button id="update" class="btn btn-danger" style="margin-left: 48px;">更新</button>
            <button class="up_cancel btn btn-primary" style="margin-left: 48px;">取消</button>
        </div>
    </div>
{% endblock %}

{% block myjs %}
    {# 删除学生 #}
    <script>
        $('.delete').click(function () {
            res = window.confirm('是否删除学生');
            return res;
        });
    </script>

    {# 增加学生 #}
    <script>
        $('#ajax_add').click(function () {
            $('.shadow, .add_model').css('display', 'block');
            {#$('.shadow, .add_model').show()#}
        });

        $('.add_cancel').click(function () {
            $('.shadow, .add_model').hide();
            window.location.href = '/students/'
        });

        $('#add').click(function () {
            var name = $('#add_student').val();
            var age = $('#add_age').val();
            var cid = $('#add_cid').val();
            {#console.log(classname);#}
            $.ajax({
                type: 'POST',
                url: '/ajax_add_student/',
                data: {'name': name, 'age': age, 'cid': cid},
                success: function (data) {
                    var res = JSON.parse(data);

                    if (res['code'] == 10000) {
                        alert(res['msg']);
                        window.location.href = '/students/';
                    } else {
                        $('#add_error').text(res['msg']);
                    }
                }
            })
        });

    </script>

    {# 更新学生 #}
    <script>
        $('.ajax_update').click(function () {
            $('.shadow, .update_model').show();
            var info = $(this).parent().prevAll();
            {#console.log(info)#}
            var age = info[1].innerText;
            var name = info[2].innerText;
            var id = info[3].innerText;
            var cid = $(info[0]).attr('clsid');

            $('#up_age').val(age);
            $('#up_name').val(name);
            $('#up_sid').val(id);
            $('#up_cid').val(cid);
        });

        $('.up_cancel').click(function () {
            $('.shadow, .update_model').hide();
            window.location.href = '/students/';
        });

        $('#update').click(function () {
            var name = $('#up_name').val();
            var age = $('#up_age').val();
            var id = $('#up_sid').val();
            var cid = $('#up_cid').val();
            {#console.log(classname,id);#}

            $.ajax({
                type: 'POST',
                url: '/ajax_update_student/',
                data: {'id': id, 'name': name, 'age': age, 'cid': cid},
                success: function (data) {
                    var res = JSON.parse(data);
                    if (res['code'] == 10000) {
                        alert(res['msg']);
                        window.location.href = '/students/';
                    } else {
                        $('#up_error').text(res['msg']);
                    }
                }
            })
        });

    </script>
{% endblock %}
# add_student.html -- 通过继承layout.html页面


{% extends 'layout.html' %}

{% block mycss %}
    <style>
        select {
            height: 34px;
            width: 203px;
            padding: 6px 12px;
            border: 1px solid #ccc;
            border-radius: 4px;
            background-color: #fff;
        }
    </style>
{% endblock %}

{% block mycontent %}
<h3>增加老师</h3>
<form action="/add_teacher/" method="post" class="form-inline">
    老师姓名:<input type="text" name="tname" class="form-control"><br>
    <div style="margin-top: 2px;margin-bottom: 10px">
        班级列表:<select name="cid" id="" multiple>
        {% for class in classes %}
            <option value="{{ class.id }}">{{ class.cname }}</option>
        {% endfor %}
    </select>
    </div>
    <span style="color:red; font-size: 12px;">{{ data }}</span><br>
    <span style="margin-left: 48px;"><input type="submit" value="添加" class="btn btn-danger"></span>
    <span style="margin-left: 40px;">
        <button class="btn btn-primary">
            <a href="/teachers/" style="color: white;text-decoration: none;">取消</a>
        </button>
    </span>
</form>
{% endblock %}
# update_student.html -- 通过继承layout.html页面

{% extends 'layout.html' %}

{% block mycss %}
    <style>
        select {
            height: 34px;
            width: 203px;
            padding: 6px 12px;
            border: 1px solid #ccc;
            border-radius: 4px;
            background-color: #fff;
        }
    </style>
{% endblock %}

{% block mycontent %}
    <h3>更新老师信息</h3>
    <form action="/update_teacher/" method="post" class="form-inline">
        <input type="hidden" name="tid" value="{{ teacher.id }}">
        姓名:<input type=" text" class="form-control" name="tname" value="{{ teacher.tname }}"><br>
        <div style="margin-top: 2px;margin-bottom: 10px">
            班级:<select name="cid" id="" multiple>
            {% for class in classes %}
                <option value="{{ class.id }}">{{ class.cname }}</option>
            {% endfor %}
        </select></div>
        <span style="color:red; font-size: 12px;">{{ data }}</span><br>
        <span style="margin-left: 48px;"><input type="submit" value="更新" class="btn btn-danger"></span>
        <span style="margin-left: 40px;">
        <button class="btn btn-primary">
            <a href="/teachers/" style="color: white;text-decoration: none;">取消</a>
        </button>
    </span>
    </form>
{% endblock %}
# urls.py

@deco
def teachers(request):
    sql = 'select teachers.id as tid,tname,cname,cid from teachers left join teacher2class on teachers.id = teacher2class.tid left join classes on classes.id = teacher2class.cid order by tid'
    res = mysql(sql)[0]
    # print(res)

    sql = 'select * from classes'
    classes = mysql(sql)[0]

    teachers = {}
    # cids = {}

    for dic in res:
        if dic['tid'] in teachers:
            teachers[dic['tid']]['cname'].append(dic['cname'])
            # cids[dic['tid']]['cids'].append(dic['cid'])

        else:
            teachers[dic['tid']] = {'tid': dic['tid'], 'tname': dic['tname'], 'cname': [dic['cname'], ]}
            # cids[dic['tid']] = {'classids': [dic['cid'], ]}

    return render(request, 'teachers.html', {'teachers': teachers.values(), 'classes': classes})


@deco
def add_teacher(request):
    sql = 'select * from classes'
    classes = mysql(sql)[0]

    if request.method == "GET":

        return render(request, 'add_teacher.html', {'classes': classes})

    else:
        tname = request.POST.get('tname')
        cids = request.POST.getlist('cid')

        if not (tname and cids):
            data = '姓名或班级不能为空'
            return render(request, 'add_teacher.html', {'classes': classes, 'data': data})

        sql = 'select * from teachers where tname=%s'
        res = mysql(sql, (tname,))[0]
        if res:
            data = '老师已存在'
            return render(request, 'add_teacher.html', {'classes': classes, 'data': data})

        sql = 'insert into teachers(tname) values(%s)'
        mysql(sql, (tname,))

        sql = 'select id from teachers where tname=%s'
        tid = mysql(sql, (tname,))[0].get('id')
        # print(tid)
        # print(cids)

        for cid in cids:
            cid = int(cid)
            sql = 'insert into teacher2class(tid,cid) values (%s,%s)'
            mysql(sql, (tid, cid))

        return redirect('/teachers/')


@deco
def del_teacher(request):
    # print(request)
    tid = request.GET.get('id')
    # print(tid)
    sql = 'delete from teacher2class where tid=%s'
    mysql(sql, (tid,))

    sql = 'delete from teachers where id=%s'
    mysql(sql, (tid,))

    return redirect('/teachers/')


@deco
def update_teacher(request):
    sql = 'select * from classes'
    classes = mysql(sql)[0]

    if request.method == 'GET':
        tid = request.GET.get('id')
        sql = 'select * from teachers where id=%s'
        teacher = mysql(sql, (tid,))[0]
        # print(teacher)
        return render(request, 'update_teacher.html', {'teacher': teacher, 'classes': classes})

    else:
        id = request.POST.get('tid')
        tname = request.POST.get('tname')
        cids = request.POST.getlist('cid')

        sql = 'select * from teachers where id=%s'
        teacher = mysql(sql, (id,))[0]

        if not (tname and cids):
            data = '名字或班级不能为空'
            return render(request, 'update_teacher.html', {'teacher': teacher, 'classes': classes, 'data': data})

        sql = 'select * from teachers where tname=%s and id != %s'
        res = mysql(sql, (tname, id))[0]
        if res:
            data = f'老师--{tname}--已存在'
            return render(request, 'update_teacher.html', {'teacher': teacher, 'classes': classes, 'data': data})

        sql = 'delete from teacher2class where tid=%s'
        mysql(sql, (id,))

        sql = 'update teachers set tname=%s where id=%s '
        mysql(sql, (tname, id))

        for cid in cids:
            cid = int(cid)
            sql = 'insert into teacher2class(tid,cid) values(%s,%s)'
            mysql(sql, (id, cid))

        return redirect('/teachers/')

ajax操作老师表

# urls.py

@deco
def ajax_add_teacher(request):
    tname = request.POST.get('tname')
    cids = request.POST.getlist('cid')

    res = {'code': None, 'msg': None}

    if not (tname and cids):
        res['code'] = 10001
        res['msg'] = '姓名或班级不能为空'
        return HttpResponse(json.dumps(res))

    sql = 'select * from teachers where tname=%s'
    resp = mysql(sql, (tname,))[1]
    if resp:
        res['code'] = 10001
        res['msg'] = f'老师---{tname}-已存在'
        return HttpResponse(json.dumps(res))

    sql = 'insert into teachers(tname) values(%s)'
    mysql(sql, (tname,))
    sql = 'select id from teachers where tname=%s'
    tid = mysql(sql, (tname,))[0].get('id')
    # tid = mysql(sql, (tname,))[0]
    print(tid)
    for cid in cids:
        cid = int(cid)
        sql = 'insert into teacher2class(tid,cid) values (%s,%s)'
        mysql(sql, (tid, cid))

    res['code'] = 10000
    res['msg'] = f'老师--{tname}--信息添加成功'
    return HttpResponse(json.dumps(res))


@deco
def ajax_update_teacher(request):
    id = request.POST.get('id')
    tname = request.POST.get('tname')
    cids = request.POST.getlist('cid')

    res = {'code': None, 'msg': None}
    if not (tname and cids):
        res['code'] = 10001
        res['msg'] = '名字或班级不能为空'
        return HttpResponse(json.dumps(res))

    sql = 'select * from teachers where tname=%s and id!=%s'
    resp = mysql(sql, (tname, id))[0]
    if resp:
        res['code'] = 10001
        res['msg'] = '老师已存在'
        return HttpResponse(json.dumps(res))

    sql = 'delete from teacher2class where tid=%s'
    mysql(sql, (id,))

    sql = 'update teachers set tname=%s where id=%s '
    mysql(sql, (tname, id))

    for cid in cids:
        cid = int(cid)
        sql = 'insert into teacher2class(tid,cid) values(%s,%s)'
        mysql(sql, (id, cid))

    res['code'] = 10000
    res['msg'] = f'老师--{tname}--更新成功'
    return HttpResponse(json.dumps(res))

posted @ 2019-08-16 21:01  蔚蓝的爱  阅读(381)  评论(0编辑  收藏  举报