Python全栈之路-Django(三)

1 学生管理

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/', aviews.del_student),
    url(r'^edit_student/', views.edit_student),
    url(r'^modal_add_class/', views.modal_add_class),
]

app01.views.py 引入的模块

from django.shortcuts import render, redirect, HttpResponse
import pymysql
from utils import sqlhelper

1.1 功能1:查看学生列表

app01.views.py

def students(request):
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='123456',
        db='db03',
        charset='utf8'
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute(
        'select student.id,student.student_name,class.class_name from student left join class on student.class_id=class.id order by id;'
    )
    student_list = cursor.fetchall()
    cursor.close()
    conn.close()
    return render(request, 'students.html', {'student_list': student_list})

templates.students.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>学生列表</h1>
<div>
    <a href="/add_student/">添加学生</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>{{ row.class_name }}</td>
                <td>
                    <a href="/edit_student/?student_id={{ row.id }}">编辑</a>
                    <a href="/del_student/?student_id={{ row.id }}">删除</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

</body>
</html>

1.2 功能2:添加学生

app01.views.py

def add_student(request):
    if request.method == 'GET':
        conn = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='123456',
            db='db03',
            charset='utf8'
        )
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cursor.execute(
            'select id,class_name from class;', []
        )
        class_list = cursor.fetchall()
        cursor.close()
        conn.close()
        return render(request, 'add_student.html', {'class_list': class_list})
    elif request.method == 'POST':
        student_name = request.POST.get('student_name')
        class_id = request.POST.get('class_id')
        print(student_name, class_id)
        conn = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='123456',
            db='db03',
            charset='utf8'
        )
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cursor.execute(
            'insert into student(student_name,class_id) values(%s,%s);',
            [student_name, class_id]
        )
        conn.commit()
        cursor.close()
        conn.close()
        return redirect('/students/')

templates.add_student.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>添加学生</h1>
    <form action="/add_student/" method="post">
        <p>学生姓名:<input type="text" name="student_name"></p>
        <p>所属班级:<select name="class_id">
            {% for row in class_list %}
            <option value="{{ row.id }}">{{ row.class_name }}</option>
            {% endfor %}
        </select></p>
        <input type="submit" value="提交">
    </form>
</body>
</html>

1.3 功能3:删除学生

app01.views.py

def del_student(request):
    student_id = request.GET.get('student_id')
    conn = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='123456',
            db='db03',
            charset='utf8'
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute(
        'delete from student where id=%s;',
        [student_id, ]
    )
    conn.commit()
    cursor.close()
    conn.close()
    return redirect('/students/')

1.4 功能4:编辑学生

utils.sqlhelper.py

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/6/29

import pymysql


def get_list(sql,args):
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='123456',
        db='db03',
        charset='utf8'
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute(sql, args)
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def get_one(sql,args):
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='123456',
        db='db03',
        charset='utf8'
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute(sql, args)
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    return result

def modify(sql,args):
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='123456',
        db='db03',
        charset='utf8'
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute(sql, args)
    conn.commit()
    cursor.close()
    conn.close()

app01.views.py

def edit_student(request):
    if request.method == 'GET':
        class_list = sqlhelper.get_list(
            'select id,class_name from class',
            []
        )
        student_id = request.GET.get('student_id')
        current_student_info = sqlhelper.get_one(
            'select id,student_name,class_id from student where id=%s;',
            [student_id, ]
        )
        return render(
            request,
            'edit_student.html',
            {'class_list': class_list, 'current_student_info': current_student_info}
        )
    elif request.method == 'POST':
        student_id = request.GET.get('student_id')
        student_name = request.POST.get('student_name')
        class_id = request.POST.get('class_id')
        sqlhelper.modify(
            'update student set student_name=%s,class_id=%s where id=%s;',
            [student_name, class_id, student_id]
        )
        return redirect('/students/')

templates.edit_student.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>编辑学生</h1>
    <form action="/edit_student/?student_id={{ current_student_info.id }}" method="post">
        <p>学生姓名 <input type="text" name="student_name" value="{{ current_student_info.student_name }}"></p>
        <p>
            所属班级
            <select name="class_id">
                {% for row in class_list %}
                    {% if row.id == current_student_info.class_id %}
                    <option selected value="{{ row.id }}">{{ row.class_name }}</option>
                    {% else %}
                    <option value="{{ row.id }}">{{ row.class_name }}</option>
                    {% endif %}
                {% endfor %}
            </select>
        </p>
        <input type="submit" value="提交">
    </form>

</body>
</html>

1.5 添加班级功能优化

PS:views中对用户提交的数据进行判断(以后会通过Form组件来判断)
app01.views.py

def add_class(request):
    if request.method == 'GET':
        return render(request, 'add_class.html')
    elif request.method == 'POST':
        class_name = request.POST.get('class_name').strip()
        if class_name:
            conn = pymysql.connect(
                host='localhost',
                port=3306,
                user='root',
                passwd='123456',
                db='db03',
                charset='utf8'
            )
            cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
            cursor.execute(
                'insert into class(class_name) values(%s);',
                [class_name, ]
            )
            conn.commit()
            cursor.close()
            conn.close()
            return redirect('/classes/')
        else:
            error_msg = '班级名称不能为空'
            return render(request, 'add_class.html', {'error_msg': error_msg})

templates.edit_class.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>添加班级</h1>
    <form action="/add_class/" method="post">
        <input type="text" name="class_name">
        <input type="submit" value="提交">{{ error_msg }}
    </form>
</body>
</html>

1.6 模态对话框(班级管理)

1.6.1 基于Form表单

(PS:Form表单提交,页面会刷新views函数返回的内容)
功能1:添加班级

app01.views.py

def modal_add_class(request):
    class_name = request.POST.get('class_name')
    sqlhelper.modify(
        'insert into class(class_name) values(%s)',
        [class_name, ]
    )
    return redirect('/classes/')

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{
            z-index: 1000;
            position: fixed;
            left: 50%;
            top: 50%;
            height: 300px;
            width: 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="/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">
            <input type="text" name="class_name">
            <input type="submit" name="提交">
        </form>
    </div>
    <script>
        function showModal(){
            document.getElementById('shadow').classList.remove('hide');
            document.getElementById('modal').classList.remove('hide');
        }
    </script>
</body>
</html>

1.6.2 基于Ajax(可以解决Form表单提交刷新的问题)

app01.views.py

def modal_add_class(request):
    class_name = request.POST.get('class_name').strip()
    print(class_name)
    if class_name:
        sqlhelper.modify(
            'insert into class(class_name) values(%s)',
            [class_name, ]
        )
        # return redirect('/classes/')

        return HttpResponse('ok')
    else:  # 页面不要刷新,提示错误信息  Form表单不能完成
        return HttpResponse('班级名称不能为空')

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{
            z-index: 1000;
            position: fixed;
            left: 50%;
            top: 50%;
            height: 300px;
            width: 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="/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>
    <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');
        }

        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);
                    }
                }
            })
        }
    </script>
</body>
</html>

Ajax操作总结:

  • 引入JQuery
  • 格式
$.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);
        }
    }
})

其他:

  • Ajax提交页面不刷新
  • 模态对话框一般都使用Ajax完成数据提交
  • 数据操作较多时使用新URL方式较好(还可以做广告)

posted on 2017-06-29 15:53  万越天  阅读(226)  评论(0编辑  收藏  举报