专栏首页python-爬虫django管理系统代码优化-分组(二)

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

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

后续进行代码更新,优化

一优化的内容

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

  • 路由进行主次分组(主要)
  • cookies有效时间设置为1小时,1小时后失效
  • 界面美化

二.创建app进行分组

1.app创建:

  • 使用pycharm创建django的时候, 加上app的名字,多个app复制改名即可
  • 命令行创建:Python manage.py startapp app的名字

2.创建后:

3.app介绍

二.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 djang分组 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 = '_k@kzje+27*@f2!lgi60!s264fm&a^!ev(g!!+)_eycn4pqv$5'

# 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',
    'classes.apps.ClassesConfig',
]

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 = 'djang分组.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 = 'djang分组.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'),)

四.路由

主路由django分组>urls.py

import pymysql
from django.conf.urls import url,include
from django.shortcuts import render, redirect


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('/classes/')
        obj.set_cookie('login', 'success',max_age=1800)
        return obj
    else:
        return render(request, 'login.html', {'msg': '登入失败'})


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 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': '登入失败'})

def run(request):
    return render(request, 'run.html')



urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^login/', login),
    url(r'^register/', register),
    url(r'^teacher/', include('teacher.urls')),
    url(r'^student/', include('student.urls')),
    url(r'^classes/', include('classes.urls')),
    url(r'', run),
]

分路由student>urls.py

from django.conf.urls import url
from django.contrib import admin
from student import views
urlpatterns = [
    url(r'',views.student),
]

分路由teacher>urls.py

from django.conf.urls import url
from django.contrib import admin
from teacher import views
urlpatterns = [
    url(r'',views.teacher),
]

分路由classes>urls.py

from django.conf.urls import url
from django.contrib import admin
from classes import views
urlpatterns = [
    url(r'^add/', views.add),
    url(r'^up/', views.up),
    url(r'^deleter/', views.show_class),
    url(r'^ajax_add/', views.ajax_add),
    url(r'^ajax_deleter/', views.ajax_deleter),
    url(r'^ajax_up/', views.ajax_up),
    url(r'^', views.show_class),
]

五.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"  style="position: absolute;top: 20%;left: 40%">
        账号: <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 style="color: red;font-size: 30px ;text-align: center">{{ 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 %}
{% block js %}
{% 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="/classes/?id={{ item.cid }}"></a></td>
                <td><a href="/classes/up/?id={{ item.cid }}&name={{ item.name }}">更新</a></td>
                <td><a href="/classes/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: "/classes/ajax_add/",
                data: {'classname': name},
                success: function (msg) {
                    if (msg == 'OK') {
                        alert('添加成功');
                        window.kk = '/classes/';
                    } 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: "/classes/ajax_up/",
                data: {'id': upid, 'name': name},
                success: function (msg) {
                    if (msg == 'OK') {
                        alert('更新成功');
                        window.kk = '/classes/';
                    } else {
                        alert('输入内容不能为空');
                    }

                }
            });
        });


        $('.deleter-button').click(function () {
            var chiose = confirm('是否删除');
            var deleter_id = $(this).attr('cid');
            if (chiose) {
                $.ajax({
                    type: "POST",
                    url: "/classes/ajax_deleter/",
                    data: {'id': deleter_id},
                    success: function (msg) {
                        if (msg == 'OK') {
                            alert('删除成功');
                            window.kk = '/classes/';
                        } 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 %}

7.首页

run.html

{% extends 'FUCK.html' %}
{% block data %}
<div style="color: red;font-size: 40px;text-align: center;">欢迎来到管理系统</div>
{% endblock %}

六.视图

学生端

student>view.py

import pymysql
from django.shortcuts import render, redirect


# Create your views here.


def login_deco(func):
    def wrapper(request):
        print(request.COOKIES)
        if request.COOKIES:
            res = func(request)
            return res
        else:
            return render(request, 'login.html', {'msg': '登入失效请重新登入'})

    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


@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': '名字不能为空'})

老师端

teacher>view.py

import pymysql
from django.shortcuts import render, redirect


# Create your views here.


def login_deco(func):
    def wrapper(request):
        print(request.COOKIES)
        if request.COOKIES:
            res = func(request)
            return res
        else:
            return render(request, 'login.html', {'msg': '登入失效请重新登入'})

    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


@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

班级端

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


# Create your views here.


def login_deco(func):
    def wrapper(request):
        print(request.COOKIES)
        if request.COOKIES:
            res = func(request)
            return res
        else:
            return render(request, 'login.html', {'msg': '登入失效请重新登入'})

    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


@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('/classes/')
                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('/classes/')


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('/classes/')


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')

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

我来说两句

0 条评论
登录 后参与评论

相关文章

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

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

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

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

    小小咸鱼YwY
  • django+pymysql搭建一个管理系统(一)

    小小咸鱼YwY
  • 在ASP.NET CORE 2.0使用SignalR技术

    上次讲SignalR还是在《在ASP.NET Core下使用SignalR技术》文章中提到,ASP.NET Core 1.x.x 版本发布中并没有包含Signa...

    yoyofx
  • 如何高效的进行腾讯云上的资源编排,一起来聊一聊Terraform

    “腾讯云IaC最佳实践”系列文章希望通过介绍Terraform、Chef和Ansible等生态产品工具及相关案例,使用户能够更好地在腾讯云上实践IaC,为腾讯云...

    生态产品团队
  • Yii2 学习笔记之数据库篇

    琯琯
  • MySQL之表的约束

    一 介绍 约束条件与数据类型的宽度一样,都是可选参数 作用:用于保证数据的完整性和一致性 主要分为: PRIMARY KEY (PK) 标识该字段为该表的...

    人生不如戏
  • MYSQL回顾(多表查询相关)

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

    VV木公子
  • Servlet与Jsp的结合使用实现信息管理系统二

    PS:前面说了抽取框架的搭建,接着就要我们开始进入网址的时候就要查到全部信息并显示在首页,我们用到的MySql数据库,具体步骤是: 创建数据库,创建表,添加信息...

    cMusketeer

扫码关注云+社区

领取腾讯云代金券