後續進行代碼更新,優化
css
優化前代碼:https://www.cnblogs.com/pythonywy/p/11345626.htmlhtml
主要
)zouye
庫:存信息相關的python
#班級表 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
庫:存帳號密碼mysql
create table info(id int,name char(30),password char(30)) charset utf8;
setting.py
jquery
""" 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
ios
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), ]
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>
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 %}
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 %}
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 %}
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 %}
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.location.href = '/classes/'; } 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: "/classes/ajax_up/", data: {'id': upid, 'name': name}, success: function (msg) { if (msg == 'OK') { alert('更新成功'); window.location.href = '/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.location.href = '/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 %}
run.htmlajax
{% extends 'FUCK.html' %} {% block data %} <div style="color: red;font-size: 40px;text-align: center;">歡迎來到管理系統</div> {% endblock %}
student
>view.py
sql
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
npm
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')