专栏首页python-爬虫django+pymysql搭建一个管理系统(一)

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.kk = '/class/';
                    } else {
                        alert('输入内容不能为空');
                        {#window.location.replace(kk);#}
                    }

                }
            });
        });


        $('.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.kk = '/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.kk = '/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.kk = '/class/';
                    } else {
                        alert('输入内容不能为空');
                        {#window.location.replace(kk);#}
                    }

                }
            });
        });


        $('.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.kk = '/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.kk = '/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 %}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • django管理系统代码优化-分组(二)

    优化前代码:https://www.cnblogs.com/pythonywy/p/11345626.html

    小小咸鱼YwY
  • Django-debug-toolbar(调试使用)

    django-debug-toolbar 是一组可配置的面板,可显示有关当前请求/响应的各种调试信息,并在单击时显示有关面板内容的更多详细信息。

    小小咸鱼YwY
  • 周末手撸管理系统(一)

    小小咸鱼YwY
  • django管理系统代码优化-分组(二)

    优化前代码:https://www.cnblogs.com/pythonywy/p/11345626.html

    小小咸鱼YwY
  • Django+xadmin打造在线教育平台(四)

    代码 github下载 七、授课机构功能 7.1.模板继承 (1)创建母板 把org-list.html拷贝到templates目录下,新建base.html...

    zhang_derek
  • MYSQL回顾(多表查询相关)

    简单的数据我们可以直接从一个表中获取,但在真实的项目中查询符合条件的数据通常需要牵扯到多张表,这就不得不使用多表查询。多表查询分为多表连接查询、符合条件链接查询...

    VV木公子
  • SpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一)

    最新项目下载地址 访问地址 ? 1.基于easyui的 增 删 改 查 2.基于poi的导出excel 3.基于 SpringMVC HandlerInte...

    小帅丶
  • Hibernate多表关系配置

    映射文件中普通字段段的配置不用写上外键,在一的一方配置文件写上set标签name属性为关联属性名,里面还有key标签有column属性关系中的外键即另一个表的外...

    木瓜煲鸡脚
  • Java 类机制(3)---- 类文件结构

    ​ 在上一篇文章中我们一起来看了一下 Java 虚拟机的类加载过程,包括虚拟机加载、验证、准备、解析和初始化 5 个大步骤,同时我们还讨论了 Java 虚拟机...

    指点
  • log4j.xml 日志只输出指定类配置

    1、日志增加appender 指定日志生成时间、格式、间隔时间。 2、category指定哪些或哪个类日志生成在文件中。 3、自定义logger避免不要将use...

    杉枫

扫码关注云+社区

领取腾讯云代金券