欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

django+pymysql搭建一个管理系统(一)

程序员文章站 2022-06-24 08:58:42
django+pymysql搭建一个管理系统(一) 一.程序架构 二.mysql表单创建 库:存信息相关的 库:存账号密码 三.settings文件的设置 四.路由 python """my2 URL Configuration The list routes URLs to views. For ......

django+pymysql搭建一个管理系统(一)

后续进行代码更新,优化

一.程序架构

django+pymysql搭建一个管理系统(一)

二.mysql表单创建

zouye库:存信息相关的

#班级表
create table classes(
cid  int primary key auto_increment,
name varchar(32) not null default ''
)engine=innodb charset=utf8;
insert into classes (name) values ('三年a班'), ('三年b班'),('三年c班');

#学生表
create table students (
sid int primary key auto_increment,
name varchar(32) not null default '',
class_id int not null default 1,
foreign key (class_id) references classes(cid)
)engine=innodb charset=utf8;
insert into students (name, class_id) values ('张三', 1),('李四', 2),('王五', 1);

#老师表
create table teacher (
tid int primary key auto_increment,
name varchar(32) not null default ''
)engine=innodb charset=utf8;
insert into teacher (name) values ('老师1'), ('老师2'),('老师3');

#关系表
create table teacher2class (
id int primary key auto_increment,
tid int not null default 1,
cid int not null default 1
)engine=innodb charset=utf8;
insert into teacher2class (tid, cid) values (1,1), (1,2),(2,1),(2,2);

userinfo库:存账号密码

create table info(id int,name char(30),password char(30)) charset utf8;

三.settings文件的设置

setting.py

"""
django settings for my2 project.

generated by 'django-admin startproject' using django 1.11.22.

for more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

for the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# build paths inside the project like this: os.path.join(base_dir, ...)
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# quick-start development settings - unsuitable for production
# see https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# security warning: keep the secret key used in production secret!
secret_key = '&biab7*wb3o@*v%3gmz%icp0do^i92iq&m0(l2es!bnui8q3@%'

# security warning: don't run with debug turned on in production!
debug = true

allowed_hosts = []

# application definition

installed_apps = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

middleware = [
    'django.middleware.security.securitymiddleware',
    'django.contrib.sessions.middleware.sessionmiddleware',
    'django.middleware.common.commonmiddleware',
    # 'django.middleware.csrf.csrfviewmiddleware',
    'django.contrib.auth.middleware.authenticationmiddleware',
    'django.contrib.messages.middleware.messagemiddleware',
    'django.middleware.clickjacking.xframeoptionsmiddleware',
]

root_urlconf = 'my2.urls'

templates = [
    {
        'backend': 'django.template.backends.django.djangotemplates',
        'dirs': [os.path.join(base_dir, 'templates')]
        ,
        'app_dirs': true,
        'options': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

wsgi_application = 'my2.wsgi.application'

# database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

databases = {
    'default': {
        'engine': 'django.db.backends.sqlite3',
        'name': os.path.join(base_dir, 'db.sqlite3'),
    }
}

# password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

auth_password_validators = [
    {
        'name': 'django.contrib.auth.password_validation.userattributesimilarityvalidator',
    },
    {
        'name': 'django.contrib.auth.password_validation.minimumlengthvalidator',
    },
    {
        'name': 'django.contrib.auth.password_validation.commonpasswordvalidator',
    },
    {
        'name': 'django.contrib.auth.password_validation.numericpasswordvalidator',
    },
]

# internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

language_code = 'en-us'

time_zone = 'utc'

use_i18n = true

use_l10n = true

use_tz = true

# static files (css, javascript, images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

static_url = '/static/'
staticfiles_dirs = (os.path.join(base_dir, 'static'),)

四.路由

urls.py

"""my2 url configuration

the `urlpatterns` list routes urls to views. for more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
examples:
function views
    1. add an import:  from my_app import views
    2. add a url to urlpatterns:  url(r'^$', views.home, name='home')
class-based views
    1. add an import:  from other_app.views import home
    2. add a url to urlpatterns:  url(r'^$', home.as_view(), name='home')
including another urlconf
    1. import the include() function: from django.conf.urls import url, include
    2. add a url to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
import pymysql
from django.conf.urls import url
from django.contrib import admin
from django.shortcuts import httpresponse, render, redirect


def login_deco(func):
    def wrapper(request):
        print(request.cookies)
        if request.cookies:
            res = func(request)
            return res
        else:
            return redirect('/login/')

    return wrapper


def mysql_to_db(db):
    conn = pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='16745',
        db=db
    )
    cursor = conn.cursor(pymysql.cursors.dictcursor)
    return cursor, conn


def login(request):
    if request.method == 'get':
        return render(request, 'login.html')
    cursor, conn = mysql_to_db('userinfo')
    user_name = request.post.get('username')
    user_pwd = request.post.get('pwd')
    sql = 'select * from info where name=%s and password=%s'
    cursor.execute(sql, (user_name, user_pwd))
    a = cursor.fetchall()
    if a:
        obj = redirect('/class/')
        obj.set_cookie('login', 'success')
        return obj
    else:
        return render(request, 'login.html', {'msg': '登入失败'})


def register(request):
    if request.method == 'get':
        return render(request, 'register.html')
    cursor, conn = mysql_to_db('userinfo')
    user_name = request.post.get('username')
    user_pwd = request.post.get('pwd')
    print(user_name, user_pwd)
    sql = 'select name from info where name=%s'
    x = cursor.execute(sql, (user_name))
    print('231')
    if not x:
        sql = 'insert into info(name,password) values(%s,%s) '
        cursor.execute(sql, (user_name, user_pwd))
        a = cursor.fetchall()
        return render(request, 'register.html', {'msg': '注册成功'})
    else:
        return render(request, 'register.html', {'msg': '登入失败'})


@login_deco
def show_class(request):
    if request.method == 'get':
        cursor, conn = mysql_to_db('zuoye')
        if not request.get:
            sql = 'select * from classes'
            cursor.execute(sql)
            info = cursor.fetchall()
            print(info)
            return render(request, 'show_class.html', {'dict_list': info})
        else:
            deleter_id = request.get.get('id')

            sql = 'delete from classes where cid=%s '
            try:
                a = cursor.execute(sql, (deleter_id,))
                conn.commit()
                obj = redirect('/class/')
                return obj
            except:
                sql = 'select * from classes'
                cursor.execute(sql)
                info = cursor.fetchall()
                obj = render(request, 'show_class.html', {'dict_list': info, 'msg': '内容有关联无法删除 '})
                return obj


def add(request):
    if request.method == 'get':
        return render(request, 'add.html')
    else:
        if not request.post.get('classname'):
            return render(request, 'add.html', {'msg': '输入内容不能为空'})
        else:
            classname = request.post.get('classname')
            print(classname)
            cursor, conn = mysql_to_db('zuoye')
            sql = 'insert into classes(name) values(%s)'
            cursor.execute(sql, (classname,))
            conn.commit()
            return redirect('/class/')


def up(request):
    id = request.get.get('id')
    name = request.get.get('name')
    print(id)
    print(name)
    if request.method == 'get':
        return render(request, 'add.html', {'name': name})
    else:
        if not request.post.get('classname'):
            return render(request, 'add.html', {'msg': '输入内容不能为空'})
        else:
            classname = request.post.get('classname')
            print(classname)
            cursor, conn = mysql_to_db('zuoye')
            sql = 'update classes set name=%s where cid = %s'
            cursor.execute(sql, (classname, id))
            conn.commit()
            return redirect('/class/')


def ajax_add(request):
    class_name = request.post.get('classname')
    if class_name:
        cursor, conn = mysql_to_db('zuoye')
        sql = 'insert into classes(name) values(%s)'
        cursor.execute(sql, (class_name,))
        conn.commit()
        return httpresponse('ok')
    else:
        return httpresponse('不能为空')


def ajax_up(request):
    print(request.post)
    class_name = request.post.get('name')
    id = request.post.get('id')
    # print(class_name,id)
    if class_name:
        cursor, conn = mysql_to_db('zuoye')
        sql = 'update classes set name=%s where cid = %s'
        cursor.execute(sql, (class_name, id))
        conn.commit()
        return httpresponse('ok')
    else:
        return httpresponse('不能为空')


def ajax_deleter(request):
    id = request.post.get('id')
    try:
        cursor, conn = mysql_to_db('zuoye')
        sql = 'delete from classes where cid=%s '
        cursor.execute(sql, (id,))
        conn.commit()
        return httpresponse('ok')
    except:
        return httpresponse('11')


@login_deco
def student(request):
    cursor, conn = mysql_to_db('zuoye')
    if request.method == 'get':
        sql_1 = 'select sid,students.name as sname,cid,classes.name as cname from students,classes where class_id=cid'
        sql_2 = 'select * from classes'
        cursor.execute(sql_1)
        student_info = cursor.fetchall()
        cursor.execute(sql_2)
        class_info = cursor.fetchall()
        return render(request, 'show_student.html', {'student': student_info, 'class': class_info})
    else:
        if request.post.get('action') == 'add':
            sql_1 = 'select sid,students.name as sname,cid,classes.name as cname from students,classes where class_id=cid'
            sql_2 = 'select * from classes'
            cursor.execute(sql_1)
            student_info = cursor.fetchall()
            cursor.execute(sql_2)
            class_info = cursor.fetchall()
            print(request.post)
            name = request.post.get('name')
            id = request.post.get('id')
            print(name, id)
            if name:
                sql = 'insert into students(name,class_id) values(%s,%s)'
                cursor.execute(sql, (name, id))
                conn.commit()
                return redirect('/student/')
            else:
                return render(request, 'show_student.html',
                              {'student': student_info, 'class': class_info, 'addmsg': '名字不能为空'})
        elif request.post.get('action') == 'up':
            print(request.post)
            sql_1 = 'select sid,students.name as sname,cid,classes.name as cname from students,classes where class_id=cid'
            sql_2 = 'select * from classes'
            cursor.execute(sql_1)
            student_info = cursor.fetchall()
            cursor.execute(sql_2)
            class_info = cursor.fetchall()
            print(request.post)
            name = request.post.get('sname')
            sid = request.post.get('sid')
            cid = request.post.get('cid')
            print(name, sid, cid)
            if name:
                sql = 'update students set name=%s,class_id=%s where sid=%s'
                cursor.execute(sql, (name, cid, sid))
                conn.commit()
                return redirect('/student/')
            else:
                return render(request, 'show_student.html',
                              {'student': student_info, 'class': class_info, 'upmsg': '名字不能为空'})


@login_deco
def teacher(request):
    cursor, conn = mysql_to_db('zuoye')
    if request.method == 'get':
        sql = 'select teacher.tid,teacher.name,group_concat(classes.name) as cname from teacher left join teacher2class on teacher.tid=teacher2class.tid left join classes on classes.cid=teacher2class.cid group by teacher.tid'
        cursor.execute(sql)
        info = cursor.fetchall()
        sq1_teacher = 'select * from teacher'
        cursor.execute(sq1_teacher)
        teacher_info = cursor.fetchall()
        sq1_teacher = 'select * from classes'
        cursor.execute(sq1_teacher)
        class_info = cursor.fetchall()
        print(info)
        print(teacher_info)
        print(class_info)
        obj = render(request, 'show_teacher.html',
                     {'info': info, 'class_info': class_info, 'teacher_info': teacher_info})
        return obj
    else:
        if request.post.get('action') == 'add':
            tid = request.post.get('tid')
            cid = request.post.get('cid')
            sql = 'insert into teacher2class(cid,tid) values(%s,%s)'
            cursor.execute(sql, (cid, tid))
            conn.commit()
            obj = redirect('/teacher/')
            return obj
        if request.post.get('action') == 'delete':

            tid = request.post.get('tid')
            cid = request.post.get('cid')
            sql = 'delete from teacher2class where cid=%s and tid=%s'
            a = cursor.execute(sql, (cid, tid))
            conn.commit()
            if a:
                obj = redirect('/teacher/')
                return obj
            else:
                sql = 'select teacher.tid,teacher.name,group_concat(classes.name) as cname from teacher left join teacher2class on teacher.tid=teacher2class.tid left join classes on classes.cid=teacher2class.cid group by teacher.tid'
                cursor.execute(sql)
                info = cursor.fetchall()
                sq1_teacher = 'select * from teacher'
                cursor.execute(sq1_teacher)
                teacher_info = cursor.fetchall()
                sq1_teacher = 'select * from classes'
                cursor.execute(sq1_teacher)
                class_info = cursor.fetchall()
                obj = render(request, 'show_teacher.html',
                             {'info': info, 'class_info': class_info, 'teacher_info': teacher_info,
                              'delete_msg': '该老师没有教这个班级'})
                return obj


def run(request):
    return redirect('/login/')


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', login),
    url(r'^register/', register),
    url(r'^class/', show_class),
    url(r'^add/', add),
    url(r'^up/', up),
    url(r'^ajax_add/', ajax_add),
    url(r'^ajax_up/', ajax_up),
    url(r'^ajax_deleter/', ajax_deleter),
    url(r'^student/', student),
    url(r'^teacher/', teacher),
    url(r'', run),
]

五.html相关文件

1.母版

fuck.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>title</title>

    <style>

        a:hover {
            cursor: url(https://www.cnblogs.com/images/cnblogs_com/pythonywy/1516412/o_hand.png), auto;
        }

        a:active {
            cursor: url(https://www.cnblogs.com/images/cnblogs_com/pythonywy/1516412/o_appstarting.png), auto;
        }

        a:focus {
            cursor: url(https://www.cnblogs.com/images/cnblogs_com/pythonywy/1516412/o_wait.png), auto;
        }

        p, code {
            cursor: url(https://www.cnblogs.com/images/cnblogs_com/pythonywy/1516412/o_ibeam.png), auto;
        }

        * {
            cursor: url(https://www.cnblogs.com/images/cnblogs_com/pythonywy/1516412/o_arrow.png), auto;
        }

        * {
            margin: 0;
            padding: 0;
        }

        .top {
            position: absolute;
            width: 100%;
            height: 100px;
            background: coral;
            background-size: 100% 100%;
        }

        .nav {
            position: absolute;
            left: 0;
            top: 100px;
            width: 200px;
            bottom: 0;
            background: chartreuse;
            text-align: center;
            overflow: auto;
            line-height: 30px;

        }

        a.class-action, a.student-action, .teacher-action {
            color: white;
            background: #80ff5d;
            padding: 10px;
            margin: 2px;
            display: block;
        }

        .data {
            position: absolute;
            left: 200px;
            top: 100px;
            bottom: 0;
            right: 0;
            background: url('https://images.cnblogs.com/cnblogs_com/pythonywy/1455150/o_111.png');
            background-size: 100% 100%;
            overflow: scroll;
        }

        .top-left {
            float: left;

            width: 200px;
            background: aqua;
            height: 100px;
            text-align: center;
            line-height: 100px;
            border-right: 2px solid white;
        }

        .top-right {
            float: right;
            text-align: center;
            line-height: 100px;
            margin-right: 50px;
        }
    </style>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-bvyiisifek1dgmjrakycuhahrg32omucww7on3rydg4va+pmstsz/k68vbdejh4u" crossorigin="anonymous">
    <style>
        {% block css%}
        {% endblock %}

        th, td {
            padding: 10px;
        }
    </style>
</head>

<body>
<div class="top">
    <div class="top-left">管理系统</div>
    <div class="top-right">
        <a href="\login\">登入</a>
        <a href="\register\">注册</a>
    </div>
</div>
<div class="nav">
    <ol>
        <li><a class="class-action" href="\classes\">班级系统</a></li>
        <li><a class="student-action" href="\student\">学生系统</a></li>
        <li><a class="teacher-action" href="\teacher\">老师系统</a></li>
    </ol>
</div>
<div class="data">
    {% block data %}
    {% endblock %}
</div>
</body>
{% block js %}
{% endblock %}
</html>

2.登入

login.html

{% extends 'fuck.html' %}
{% block data %}
    <form action="/login/" method="post">
        账号: <input type="text" name="username"><br>
        密码: <input type="password" name="pwd"><br>
        <input type="submit" value="提交">
    </form>
    <a href="http://127.0.0.1:8000/register/">去注册</a>
    <div>{{ msg }}</div>
{% endblock %}

3.注册

register.html

{% extends 'fuck.html' %}
{% block data %}
    <form action="/register/" method="post">
    注册账号: <input type="text" name="username"><br>
    注册密码: <input type="password" name="pwd"><br>
    <input type="submit" value="提交">
</form>
<a href="http://127.0.0.1:8000/login/">去登入</a>
<div>{{msg}}</div>
{% endblock %}

4.学生相关

show_student.html

{% extends 'fuck.html' %}
{% block css %}
    table {
    position: absolute;
    top: 28%;
    left: 0%;
    color: #000000;
    width: 100%;
    }
{% endblock %}}
{% block data %}

    <table border="2px">
        <thead>
        <tr>
            <th>学生id</th>
            <th>学生名字</th>
            <th>班级名称</th>
        </tr>
        </thead>
        <tbody>
        {% for item in student %}
            <tr>
                <td>{{ item.sid }}</td>
                <td>{{ item.sname }}</td>
                <td>{{ item.cname }}</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    <form method="post">
        <input type="text" style="visibility: hidden" name="action" value="add">

        可选择班级<select name="id" id="">
        {% for item in class %}
            <option value="{{ item.cid }}">{{ item.name }}</option>
        {% endfor %}

    </select>
        添加的学生名称<input type="text" name="name">
        <input type="submit">
    </form>
    <div class="add-msg">{{ addmsg }}</div>


    <form method="post">
        <input type="text" style="visibility: hidden" name="action" value="up">
        修改的学生<select name="sid" id="">
        {% for item in student %}
            <option value="{{ item.sid }}">{{ item.sname }}</option>
        {% endfor %}
    </select>
        可选择班级<select name="cid" id="">
        {% for item in class %}
            <option value="{{ item.cid }}">{{ item.name }}</option>
        {% endfor %}
    </select>
        输入修改的名字<input type="text" name="sname">
        <input type="submit">
    </form>
    <div class="up-msg">{{ upmsg }}</div>
{% endblock %}

5.老师相关

show_teacher.html

{% extends 'fuck.html' %}
{% block data %}

    <table border="2px" class="table table-bordered">
        <thead>
        <tr>
            <th>id</th>
            <th>老师名称</th>
            <th>班级</th>

        </tr>
        </thead>
        <tbody>
        {% for item in info %}
            <tr>
                <td>{{ item.tid }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.cname }}</td>

            </tr>
        {% endfor %}
        </tbody>
    </table>
    <div>{{ msg }}</div>

    <form class="action" method="post">
        <input type="text" name="action" value="add" style="display: none">
        已有老师教添加班级<select name="tid" id="">
        {% for foo in teacher_info %}
            <option value="{{ foo.tid }}">{{ foo.name }}</option>
        {% endfor %}
    </select>
        <select name="cid" id="">
            {% for class in class_info %}
                <option value="{{ class.cid }}">{{ class.name }}</option>
            {% endfor %}
        </select>
        <input type="submit">
    </form>


    <form class="action" method="post">
        <input type="text" name="action" value="delete" style="display: none">
        已有老师教删除班级<select name="tid" id="">
        {% for foo in teacher_info %}
            <option value="{{ foo.tid }}">{{ foo.name }}</option>
        {% endfor %}
    </select>
        </select>
        <select name="cid" id="">
            {% for class in class_info %}
                <option value="{{ class.cid }}">{{ class.name }}</option>
            {% endfor %}
        </select>
        <input type="submit">
    </form>
    <span style="color: red"> {{ delete_msg }} </span>

{% endblock %}
{% block js %}
    <script
            src="http://code.jquery.com/jquery-1.12.4.min.js"
            integrity="sha256-zosebrlbnqzlpnkikedrpv7loy9c27hhq+xp8a4mxaq="
            crossorigin="anonymous"></script>
    <script>
        $('.add-button').click(function () {
            $('#add-back,#add-window').css('display', 'block');
        });

        $('.add-window-button').click(function () {
            $('#add-back,#add-window').css('display', 'none');
        });

        $('.add-submit').click(function () {
            var name = $('.add-text').val();

            $.ajax({
                type: "post",
                url: "/ajax_add/",
                data: {'classname': name},
                success: function (msg) {
                    if (msg == 'ok') {
                        alert('添加成功');
                        window.location.href = '/class/';
                    } else {
                        alert('输入内容不能为空');
                        {#window.location.replace(location.href);#}
                    }

                }
            });
        });


        $('.up-button').click(function () {
            $('#up-back,#up-window').css('display', 'block');
            window.upid = $(this).attr('cid');
            $('.up-text').val($(this).attr('classname'));
            console.log(upid);

        });

        $('.up-window-button').click(function () {
            $('#up-back,#up-window').css('display', 'none');
        });

        $('.up-submit').click(function () {
            var name = $('.up-text').val();
            console.log(name);
            console.log(upid);
            $.ajax({
                type: "post",
                url: "/ajax_up/",
                data: {'id': upid, 'name': name},
                success: function (msg) {
                    if (msg == 'ok') {
                        alert('更新成功');
                        window.location.href = '/class/';
                    } else {
                        alert('输入内容不能为空');
                    }

                }
            });
        });


        $('.deleter-button').click(function () {
            var chiose = confirm('是否删除');
            var deleter_id = $(this).attr('cid');
            if (chiose) {
                $.ajax({
                    type: "post",
                    url: "/ajax_deleter/",
                    data: {'id': deleter_id},
                    success: function (msg) {
                        if (msg == 'ok') {
                            alert('删除成功');
                            window.location.href = '/class/';
                        } else {
                            alert('内容有关联无法删除');
                        }

                    }
                });
            }
        });


        $('.deleter-a').click(function () {
            var chiose = confirm('是否删除');
            return chiose
        })
    </script>
{% endblock %}

6.班级相关

show_class.html

{% extends 'fuck.html' %}
{% block css %}


    table{
    position: absolute;
    top: 0;
    left: 0;
    color: #000000;
    width: 100%;
    }

    #up-back, #add-back {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: none;
    }

    #up-window, #add-window {
    position: fixed;
    top: 20%;
    left: 37%;
    width: 400px;
    height: 200px;
    background-color: beige;
    text-align: center;
    display: none;
    }

{% endblock %}}
{% block data %}

    <table border="2px" class="table-hover">
        <thead>
        <tr>
            <th>id</th>
            <th>班级名称</th>
            <th colspan="3">功能</th>
            <th colspan="3">ajax功能</th>
        </tr>
        </thead>
        <tbody>
        {% for item in dict_list %}
            <tr>
                <td>{{ item.cid }}</td>
                <td>{{ item.name }}</td>
                <td><a class='deleter-a glyphicon glyphicon-trash' href="/class/?id={{ item.cid }}"></a></td>
                <td><a href="/up/?id={{ item.cid }}&name={{ item.name }}">更新</a></td>
                <td><a href="/add/">添加</a></td>
                <td>
                    <button class='deleter-button glyphicon glyphicon-trash'
                            cid={{ item.cid }} classname={{ item.name }}></button>
                </td>
                <td>
                    <button class='up-button' cid={{ item.cid }} classname={{ item.name }}>更新</button>
                </td>
                <td>
                    <button class='add-button' cid={{ item.cid }} classname={{ item.name }}>添加</button>
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    <div>{{ msg }}</div>

    <div id="up-back"></div>
    <div id="up-window">
        <input type="text" name="id" style="visibility: hidden"><br>
        修改名称:<input type="text" class='up-text' name="'classname">
        <input class='up-submit' type="button" value="提交">
        <button class="up-window-button">取消</button>
    </div>
    <div id="add-back"></div>
    <div id="add-window">
        <input type="text" name="id" style="visibility: hidden"><br>
        添加名称:<input type="text" class='add-text' name="'classname">
        {#    <button class="add-submit">提交</button>#}
        <input class='add-submit' type="button" value="提交">
        <button class="add-window-button">取消</button>
    </div>


{% endblock %}
{% block js %}
    <script
            src="http://code.jquery.com/jquery-1.12.4.min.js"
            integrity="sha256-zosebrlbnqzlpnkikedrpv7loy9c27hhq+xp8a4mxaq="
            crossorigin="anonymous"></script>
    <script>
        $('.add-button').click(function () {
            $('#add-back,#add-window').css('display', 'block');
        });

        $('.add-window-button').click(function () {
            $('#add-back,#add-window').css('display', 'none');
        });

        $('.add-submit').click(function () {
            var name = $('.add-text').val();

            $.ajax({
                type: "post",
                url: "/ajax_add/",
                data: {'classname': name},
                success: function (msg) {
                    if (msg == 'ok') {
                        alert('添加成功');
                        window.location.href = '/class/';
                    } else {
                        alert('输入内容不能为空');
                        {#window.location.replace(location.href);#}
                    }

                }
            });
        });


        $('.up-button').click(function () {
            $('#up-back,#up-window').css('display', 'block');
            window.upid = $(this).attr('cid');
            $('.up-text').val($(this).attr('classname'));
            console.log(upid);

        });

        $('.up-window-button').click(function () {
            $('#up-back,#up-window').css('display', 'none');
        });

        $('.up-submit').click(function () {
            var name = $('.up-text').val();
            console.log(name);
            console.log(upid);
            $.ajax({
                type: "post",
                url: "/ajax_up/",
                data: {'id': upid, 'name': name},
                success: function (msg) {
                    if (msg == 'ok') {
                        alert('更新成功');
                        window.location.href = '/class/';
                    } else {
                        alert('输入内容不能为空');
                    }

                }
            });
        });


        $('.deleter-button').click(function () {
            var chiose = confirm('是否删除');
            var deleter_id = $(this).attr('cid');
            if (chiose) {
                $.ajax({
                    type: "post",
                    url: "/ajax_deleter/",
                    data: {'id': deleter_id},
                    success: function (msg) {
                        if (msg == 'ok') {
                            alert('删除成功');
                            window.location.href = '/class/';
                        } else {
                            alert('内容有关联无法删除');
                        }

                    }
                });
            }
        });


        $('.deleter-a').click(function () {
            var chiose = confirm('是否删除');
            return chiose
        })
    </script>
{% endblock %}

add.html

{% extends 'fuck.html' %}
{% block data %}
    <form action="" method="post">
        添加班级名称:<input type="text" name="classname">
        <input type="submit" value="提交">
        <div>{{ msg }}</div>
    </form>
{% endblock %}

up.html

{% extends 'fuck.html' %}
{% block data %}
    <form action="" method="post">
    跟换班级名称:<input type="text" name="classname" placeholder="{{test}}">
    <input type="submit" value="提交">
    <div>{{msg}}</div>
</form>

{% endblock %}