Python全栈之路-Django(四)

bootstrap http://v3.bootcss.com/
fontawesome http://fontawesome.io/

1 利用js阻止默认事件的触发

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <a href="http://www.baidu.com/" onclick="return func();">对话框添加</a>
    <script>
        function func() {
            alert(123)
            return true;  // 默认事件会触发
            return false;  // 默认事件不会触发
        }
    </script>
</body>
</html>

2 Ajax操作

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^classes/', views.classes),
    url(r'^add_class/', views.add_class),
    url(r'^del_class/', views.del_class),
    url(r'^edit_class/', views.edit_class),
    url(r'^students/', views.students),
    url(r'^add_student/', views.add_student),
    url(r'^del_student/', views.del_student),
    url(r'^edit_student/', views.edit_student),
    url(r'^modal_add_class/', views.modal_add_class),
    url(r'^modal_edit_class/', views.modal_edit_class),
    url(r'^modal_add_student/', views.modal_add_student),
    url(r'^modal_edit_student/', views.modal_edit_student),
    url(r'^teachers/', views.teachers),
]

2.1 功能1:编辑班级

app01.views.py

def modal_edit_class(request):
    ret = {'status': True, 'message': None}
    try:
        class_id = request.POST.get('class_id')
        class_name = request.POST.get('class_name').strip()
        if class_name:
            sqlhelper.modify(
                'update class set class_name=%s where id=%s',
                [class_name, class_id]
            )
        else:
            ret['status'] = False
            ret['message'] = '班级名称不能为空'
    except Exception as e:
        ret['status'] = False
        ret['message'] = str(e)
    return HttpResponse(json.dumps(ret))

templates.classes.html

<!DOCTYPE html>
<html lang="en">
<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;
        }
        #modal,#editModal{
            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>班级列表</h1>
    <div>
        <a href="/add_class/">添加班级</a>
        <a href="#" onclick="showModal();">对话框添加</a>
    </div>
    <table>
        <thead>
        <tr>
            <th>ID</th>
            <th>班级名称</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
            {% for row in class_list %}
            <tr>
                <td>{{ row.id }}</td>
                <td>{{ row.class_name }}</td>
                <td>
                    <a href="/del_class/?id={{ row.id }}">删除</a>
                    <a href="#" onclick="return modalEdit(this);">对话框编辑</a>
                    <a href="/edit_class/?id={{ row.id }}">编辑</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    <div id="shadow" class="hide"></div>
    <div id="modal" class="hide">
        <form action="/modal_add_class/" method="post">
            <p><input type="text" name="class_name" id="class_name"></p>
            <input type="button" value="提交" onclick="AjaxSend();">
            <input type="button" value="取消" onclick="cancleModal();">
            <span id="errormsg"></span>
        </form>
    </div>
    <div id="editModal" class="hide">
        <h3>编辑框</h3>
        <form action="/modal_add_class/" method="post">
            <p><input type="text" name="class_name" id="edit_class_name"></p>
            <p><input type="text" name="class_id" style="display: none" id="edit_class_id"></p>
            <input type="button" value="提交" onclick="editAjaxSend();">
            <input type="button" value="取消" onclick="cancleModal();">
            <span id="errormsg"></span>
        </form>
    </div>

    <script src="/static/jquery-3.2.1.min.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('editModal').classList.add('hide');
        }

        function AjaxSend() {
            $.ajax({
                url: '/modal_add_class/', // 提交地址
                type: 'POST',             // 提交方式
                data: {'class_name': $('#class_name').val()},  // 提交数据
                success: function (data) { // 当服务端处理完成后,返回数据时,该函数自动调用
                    // data 为返回的数据
                    if(data == 'ok'){
{#                        location.href='/classes/';#}
                        location.reload();
                    }else{
                        $('#errormsg').text(data);
                    }
                }
            })
        }
        
        function modalEdit(self) {
            document.getElementById('shadow').classList.remove('hide');
            document.getElementById('editModal').classList.remove('hide');
            /*
            1.获取当前标签
            2.当前标签父标签的上方的标签
            3.获取当前行班级名,放入编辑框
             */
            var row = $(self).parent().prevAll();
            var content = $(row[0]).text();
            $('#edit_class_name').val(content);
            var class_id=$(row[1]).text();
            $('#edit_class_id').val(class_id)
        }
        
        function editAjaxSend() {
            var class_id = $('#edit_class_id').val();
            var class_name = $('#edit_class_name').val();

            $.ajax({
                url:'/modal_edit_class/',
                type:'POST',
                data: {'class_id':class_id,'class_name':class_name},
                success:function (arg) {
                    // arg 是字符串类型
                    // JSON.parse(字符串) => 对象
                    // JSON.stringify(对象) => 字符串
                    arg = JSON.parse(arg);
                    if(arg.status){
                        location.reload();
                    }else{
                        alert(arg.message);
                    }
                }
            })
        }
    </script>
</body>
</html>

2.2 学生操作:

2.2.1 功能1:添加学生

app01.views.py

def students(request):
    student_list = sqlhelper.get_list(
        'select student.id,student.student_name,class.class_name 
        from student left join class on student.class_id=class.id 
        order by id;',
        []
    )

    class_list = sqlhelper.get_list(
        'select id,class_name from class;',
        []
    )
    return render(request, 'students.html', {'student_list': student_list, 'class_list': class_list})
def modal_add_student(request):
    ret = {'status': True, 'message': None}
    try:
        student_name = request.POST.get('student_name').strip()
        class_id = request.POST.get('class_id')
        print(student_name, class_id)
        if student_name:
            sqlhelper.modify(
                'insert into student(student_name,class_id) values(%s,%s)',
                [student_name, class_id, ]
            )
        else:
            ret['status'] = False
            ret['message'] = '学生姓名不能为空'
            return HttpResponse(json.dumps(ret))
    except Exception as e:
        ret['status'] = False
        ret['message'] = str(e)
    return HttpResponse(json.dumps(ret))

templates.students.html

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

    </style>
</head>
<body>
<h1>学生列表</h1>
<div>
    <a href="/add_student/">添加学生</a>
    <a href="#" id="addModal">对话框添加</a>
    <table>
        <thead>
            <tr>
                <td>ID</td>
                <td>学生姓名</td>
                <td>所属班级</td>
                <td>操作</td>
            </tr>
        </thead>
        <tbody>
            {% for row in student_list %}
            <tr>
                <td>{{ row.id }}</td>
                <td>{{ row.student_name }}</td>
                <td cid="{{ row.class_id }}">{{ row.class_name }}</td>
                <td>
                    <a href="/edit_student/?student_id={{ row.id }}">编辑</a>
                    <a href="#" class="modalBtnEdit">对话框编辑</a>
                    <a href="/del_student/?student_id={{ row.id }}">删除</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<div class="shadow hide"></div>
<div class="add_modal hide">
    <p>
        <input id="addStudentName" type="text" name="student_name" placeholder="学生姓名">
    </p>
    <p>班级
        <select id="addClassId" name="class_id">
            {% for row in class_list %}
            <option value="{{ row.id }}">{{ row.class_name }}</option>
            {% endfor %}
        </select>
    </p>
    <input id="btnAdd" type="button" value="添加">
    <span id="ErrorMsg"></span>
</div>

<div class="edit_modal hide">
    <h1>编辑学生信息</h1>
    <p>
        学生姓名 <input id="editStudentName" type="text" name="student_name" placeholder="学生姓名">
        <input type="text" id="editStudentId" style="display: none">
    </p>

    <p>班级
        <select id="editClassId" name="class_id">
            {% for row in class_list %}
            <option value="{{ row.id }}">{{ row.class_name }}</option>
            {% endfor %}
        </select>
    </p>
    <input id="btnEdit" type="button" value="更新">
    <span id="editErrorMsg"></span>
</div>
<script src="/static/jquery-3.2.1.min.js"></script>
<script>
    $(function () {  //当页面框架加载完成之后执行
        $('#addModal').click(function () {
            // JQuery绑定的事件也可以阻止默认事件发生
            // return false
            $('.shadow').removeClass('hide');
            $('.add_modal').removeClass('hide');
        });
        $('#btnAdd').click(function () {
            $.ajax({
                url:'/modal_add_student/',
                type: 'POST',
                data: {'student_name': $('#addStudentName').val(),'class_id': $('#addClassId').val()},
                success:function (arg) {
                    arg = JSON.parse(arg);
                    if(arg.status){
                        location.reload();
                    }else{
                        $('#ErrorMsg').text(arg.message);
                    }
                }
            })
        });
        $('.modalBtnEdit').click(function () {
            $('.shadow,.edit_modal').removeClass('hide')
            /*
            1.获取当前标签 $(this)
             */
            var tds = $(this).parent().prevAll();
            var student_id = $(tds[2]).text();
            var student_name = $(tds[1]).text();
            var class_id = $(tds[0]).attr('cid');
{#            console.log(student_id,student_name,class_id)#}
            $('#editStudentName').val(student_name);
            $('#editStudentId').val(student_id);
            $('#editClassId').val(class_id);
        });
        $('#btnEdit').click(function () {
            var student_id = $('#editStudentId').val();
            var student_name = $('#editStudentName').val();
            var class_id = $('#editClassId').val();
            $.ajax({
                url: '/modal_edit_student/',
                type: 'POST',
                data: {'student_id': student_id,'student_name': student_name,'class_id': class_id},
                dataType: 'JSON', // JSON.parse(arg) 自动反序列化
                success: function (arg) {
{#                    arg = JSON.parse(arg);#}
                    if (arg.status){
                        location.reload();
                    }else{
                        $('#editErrorMsg').text(arg.message);
                    }
                }
            })
        })
    })
</script>
</body>
</html>

2.2.2 功能2:编辑学生

app01.views.py

def modal_edit_student(request):
    ret = {'status': True, 'message': None}
    try:
        student_id = request.POST.get('student_id')
        student_name = request.POST.get('student_name').strip()
        class_id = request.POST.get('class_id')
        if student_name:
            sqlhelper.modify(
                'update student set student_name=%s,class_id=%s where id=%s',
                [student_name, class_id, student_id]
            )
        else:
            ret['status'] = False
            ret['message'] = '学生姓名不能为空'
    except Exception as e:
        ret['status'] = False
        ret['message'] = str(e)
    return HttpResponse(json.dumps(ret))

3 多对多操作:

3.1 功能1:查看老师班级关系列表

app01.views.py

def teachers(request):
    teacher_list = sqlhelper.get_list(
        'select teacher.id as teacher_id,teacher.teacher_name,class.class_name 
        from teacher left join teacher_class on teacher.id=teacher_class.teacher_id 
        left join class on teacher_class.class_id=class.id order by teacher.id;',
        []
    )
    result = {}
    for item in teacher_list:
        teacher_id = item['teacher_id']
        if item in result:
            result[teacher_id]['class_name'].append(item['class_name'])
        else:
            result[teacher_id] = {
                'teacher_id': teacher_id,
                'teacher_name': item['teacher_name'],
                'class_name': [item['class_name'], ]
            }
    return render(request, 'teachers.html', {'teacher_list': result.values()})

templates.teachers.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>老师列表</h1>

    <table>
        <thead>
        <tr>
            <th>ID</th>
            <th>老师姓名</th>
            <th>任教班级</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
            {% for row in teacher_list %}
            <tr>
                <td>{{ row.teacher_id }}</td>
                <td>{{ row.teacher_name }}</td>
                <td>
                    {% for item in  row.class_name %}
                        <span style="display: inline-block;margin-right: 10px;">{{ item }}</span>
                    {% endfor %}
                </td>
                <td>
                    <a>删除</a>
                    <a>编辑</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>
原文地址:https://www.cnblogs.com/wanyuetian/p/7096893.html