Django 学生管理
models.py
#models from django.db import models # Create your models here. class Classes(models.Model): ''' 班级表 ''' title = models.CharField(max_length=32) a = models.ManyToManyField('Teacher', related_name='sss') class Teacher(models.Model): ''' 老师表 ''' name = models.CharField(max_length=32) class Student(models.Model): ''' 学生表 ''' username = models.CharField(max_length=32) age = models.IntegerField(default=18) gender = models.IntegerField() cs = models.ForeignKey(Classes, on_delete=models.CASCADE)
urls.py
from django.contrib import admin from django.urls import path, re_path from app01.views import classes, student, teacher from app01.views import ajax urlpatterns = [ path('admin/', admin.site.urls), path('classes.html', classes.get_classes), path('edit_classes.html', classes.edit_classes), path('add_classes.html', classes.add_classes, name='add_classes'), path('del_classes.html', classes.del_classes), re_path('^set_teacher.html', classes.set_teacher), re_path(r'^students.html', student.get_student), re_path('^edit_students.html', student.edit_student), re_path(r'^add_students.html', student.add_student, name='add_student'), path('del_student.html', student.del_student), re_path(r'^teachers.html', teacher.get_teacher), re_path('^edit_teachers.html', teacher.edit_teacher), re_path(r'^add_teachers.html', teacher.add_teacher), re_path('^del_teacher.html', teacher.del_teacher), re_path('^set_classes.html', teacher.set_classes), re_path('ajax1.html$', ajax.ajax1), re_path('ajax2.html$', ajax.ajax2), re_path('ajax3.html$', ajax.ajax3), re_path('ajax4.html$', ajax.ajax4), re_path('removeclass.html$',ajax.remove_class), ]
-views
classes.py
from django.shortcuts import render, redirect from app01 import models from django.views.decorators.csrf import csrf_exempt def get_classes(request): cls_list = models.Classes.objects.all() for row in cls_list: print(row.id, row.title, row.a.all()) return render(request, 'get_classes.html', {'cls_list': cls_list}) @csrf_exempt def add_classes(request): if request.method == "GET": return render(request, 'add_classes.html') elif request.method == "POST": title = request.POST.get('title') models.Classes.objects.create(title=title) return redirect('/classes.html') def del_classes(request): nid = request.GET.get('nid') models.Student.objects.filter(cs_id=nid).update(cs_id=10) cs_obj = models.Classes.objects.filter(id=nid).first() cs_obj.a.clear() models.Classes.objects.filter(id=nid).delete() return redirect('/classes.html') @csrf_exempt def edit_classes(request): if request.method == "GET": nid = request.GET.get('nid') cs_obj = models.Classes.objects.filter(id=nid).first() print(cs_obj) return render(request, 'edit_classes.html', {'cs_obj': cs_obj}) elif request.method == "POST": nid = request.GET.get('nid') t = request.POST.get('name') models.Classes.objects.filter(id=nid).update(title=t) return redirect('/classes.html') def set_teacher(request): if request.method == "GET": nid = request.GET.get('nid') cls_obj = models.Classes.objects.filter(id=nid).first() print(cls_obj) cls_teacher_list = cls_obj.a.all().values_list('id', 'name') print(cls_teacher_list) # 当前班级任课老师列表 id_list = list(zip(*cls_teacher_list))[0] \ if list(zip(*cls_teacher_list)) \ else [] all_teacher_list = models.Teacher.objects.all() return render(request, 'set_teacher.html', {'cls_teacher_list': cls_teacher_list, 'all_teacher_list': all_teacher_list, 'id_list': id_list, 'nid': nid, }) elif request.method == "POST": nid = request.GET.get("nid") ids = request.POST.getlist("teacher_ids") obj = models.Classes.objects.filter(id=nid).first() obj.a.set(ids) return redirect('classes.html')
-student.py
from django.shortcuts import render, redirect from app01 import models from django.views.decorators.csrf import csrf_exempt def get_student(request): stu_list = models.Student.objects.all() cs_list = models.Classes.objects.all() for row in stu_list: print(row.username, row.gender, row.age, row.cs.title) return render(request, 'get_student.html', {"stu_list": stu_list, 'cs_list': cs_list}) @csrf_exempt def add_student(request): if request.method == "GET": cs_list = models.Classes.objects.all() for i in cs_list: print(i.title) return render(request, 'add_students.html', {'cs_list': cs_list}) elif request.method == "POST": u = request.POST.get("username") a = request.POST.get("age") g = request.POST.get("gender") c = request.POST.get("cs") models.Student.objects.create( username=u, age=a, gender=g, cs_id=c ) return redirect('/students.html') def del_student(request): nid = request.GET.get("nid") models.Student.objects.filter(id=nid).delete() return redirect('/students.html') def edit_student(request): if request.method == 'GET': nid = request.GET.get('nid') cs_list = models.Classes.objects.all() stu_list = models.Student.objects.filter(id=nid).first() return render(request, 'edit_students.html', {"stu_list": stu_list, 'cs_list': cs_list}) elif request.method == "POST": nid = request.GET.get('nid') u = request.POST.get("name") a = request.POST.get("age") g = request.POST.get("gender") c = request.POST.get("cs") models.Student.objects.filter(id=nid).update(username=u, age=a, gender=g, cs_id=c) return redirect('/students.html')
-teacher.py
from django.shortcuts import render, redirect, HttpResponse from app01 import models from django.views.decorators.csrf import csrf_exempt def get_teacher(request): teacher_list = models.Teacher.objects.all() for i in teacher_list: print(i.name, i.id, i.sss.all()) return render(request, 'get_teachers.html', locals()) def add_teacher(request): if request.method == "GET": return render(request, 'add_teachers.html') elif request.method == "POST": u = request.POST.get('name') models.Teacher.objects.create(name=u) return redirect('teachers.html') def edit_teacher(request): if request.method == 'GET': nid = request.GET.get('nid') t_obj = models.Teacher.objects.filter(id=nid).first() cls_teacher_list = t_obj.sss.all().values_list('id', 'title') id_list = list(zip(*cls_teacher_list))[0] all_classes_list = models.Classes.objects.all() print(t_obj) return render(request, 'edit_teachers.html', locals()) elif request.method == 'POST': nid = request.GET.get('nid') u = request.POST.get('name') models.Teacher.objects.filter(id=nid).update(name=u) ids = request.POST.getlist("cs_ids") obj = models.Teacher.objects.filter(id=nid).first() obj.sss.set(ids) return redirect('/teachers.html') def del_teacher(request): nid = request.GET.get("nid") obj = models.Teacher.objects.filter(id=nid).first() models.Teacher.objects.filter(id=nid).delete() obj.sss.clear() return redirect('/teachers.html') def set_classes(request): if request.method == "GET": nid = request.GET.get('nid') th_obj = models.Teacher.objects.filter(id=nid).first() print(th_obj) cls_teacher_list = th_obj.sss.all().values_list('id', 'title') # for i in cls_teacher_list: # print(i.title) # 当前班级任课老师列表 id_list = list(zip(*cls_teacher_list))[0] \ if list(zip(*cls_teacher_list)) \ else [] all_classes_list = models.Classes.objects.all() # id_list = [] return render(request, 'set_classes.html', locals()) elif request.method == "POST": nid = request.GET.get("nid") ids = request.POST.getlist("cs_ids") obj = models.Teacher.objects.filter(id=nid).first() obj.sss.set(ids) return redirect('/teachers.html')
-templates
add_classes.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> {% csrf_token %} <div> <form action="{% url 'add_classes' %}" method="post"> <input type="text" name="title"> <input type="submit"> </form> </div> </body> </html>
add_students.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <h3>添加用户</h3> <form action="/add_students.html" method="POST"> {% csrf_token %} <p><input type="text" name="username" placeholder="用户名"/></p> <p><input type="text" name="age" placeholder="年龄"/></p> <p>性别 <select name="gender" size="1"> <option value="1">男</option> <option value="2">女</option> <option value="3">保密</option> </select> </p> <p>班级 <select name="cs" size="1"> {% for i in cs_list %} <option value="{{ i.id }}">{{ i.title }}</option> {% endfor %} </select> </p> <p><input type="submit"></p> </form> </body> </html>
add_teachers.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <div> <form action="/add_teachers.html" method="POST"> {% csrf_token %} <p><input type="text" name="name">教师姓名</p> <p><input type="submit"></p> </form> </div> </body> </html>
edit_classes.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <div> <form method="post" action="/edit_classes.html?nid={{ cs_obj.id }}"> {% csrf_token %} {# <input type="text" name="id" value="{{ cs_obj.id }}">#} <input type="text" name="name" value="{{ cs_obj.title }}" /> <input type="submit" value="提交" /> </form> </div> </body> </html>
edit_students.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <div> <div> <form method="post" action="/edit_students.html?nid={{ stu_list.id }}"> {% csrf_token %} {# <input type="text" name="id" value="{{ cs_obj.id }}">#} <input type="text" name="name" value="{{ stu_list.username }}" /> <input type="text" name="age" value="{{ stu_list.age }}" /> <p> <select name="gender" size="1"> <option value="1">男</option> <option value="2">女</option> <option value="3">保密</option> </select> </p> <p> <select name="cs" size="1"> {% for row in cs_list %} <option value="{{ row.id }}">{{ row.title }}</option> <{% endfor %} </select> </p> <input type="submit" value="提交" /> </form> </div> </body> </html>
edit_teachers.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <form action="/edit_teachers.html?nid={{ t_obj.id }}" method="post"> {% csrf_token %} <p><input type="text" name="name" value="{{ t_obj.name }}"></p> <select multiple size="5" name="cs_ids"> {% for item in all_classes_list %} {% if item.id in id_list %} <option value="{{ item.id }}" selected="selected">{{ item.title }}</option> {% else %} <option value="{{ item.id }}">{{ item.title}}</option> {% endif %} {% endfor %} </select> <input type="submit" value="提交"> </form> </body> </html>
get_classes.html
<!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } .btn { display: inline-block; padding: 5px 15px; background: #b8860b; color: #ffffff; cursor: pointer; } .content { height: 1800px; background-color: #336699; } .shade { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: #99abcd; opacity: 0.3; } .model { width: 200px; height: 200px; background-color: #ccccff; position: absolute; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; } .model .cancel { float: right; } .hide { display: none; } </style> </head> <body> <div> <button onclick="show()">添加</button> <div class="content"> <table border="1"> <thead> <tr> <th>ID</th> <th>名称</th> <th>任课老师</th> </tr> </thead> <tbody> {% for row in cls_list %} <tr nid="{{ row.id }}"> <td> {{ row.id }} </td> <td> {{ row.title }} </td> <td> {% for item in row.a.all %} <span>{{ item.name }}</span> {% endfor %} </td> <td> <a href="/del_classes.html?nid={{ row.id }}">删除</a> | <a onclick="removeClass(this)" href="javascript:void(0);">Ajax删除</a> | <a href="/edit_classes.html?nid={{ row.id }}">编辑</a> | <a href="/set_teacher.html?nid={{ row.id }}">分配老师</a> </td> </tr> {% endfor %} </tbody> </table> </div> <div class="shade hide"> </div> <div class="model hide"> <button class="cancel" onclick="cancel()"> × </button> <input type="text" id="title"> <div class="btn" onclick="addClass(this);">提交</div> </div> </div> <script src="/static/jquery-3.5.1.min.js"></script> <script> function show() { var ele_shade = document.getElementsByClassName("shade")[0]; var ele_model = document.getElementsByClassName("model")[0]; ele_model.classList.remove("hide"); ele_shade.classList.remove("hide"); } function cancel() { var ele_shade = document.getElementsByClassName("shade")[0]; var ele_model = document.getElementsByClassName("model")[0]; ele_model.classList.add("hide"); ele_shade.classList.add("hide"); } function removeClass(cs) { var nid = $(cs).parent().parent().attr('nid'); $.ajax({ url: '/removeclass.html', type: 'GET', data: {nid: nid}, success: function (arg) { if (arg == '成功') { //window.location.reload(); $(cs).parent().parent().remove() } else { alert(arg); } } }) } function submitForm() { var u = $('#username').val(); var p = $('#password').val(); $.ajax({ url: '/ajax2.html', type: 'GET', data: {username: u, password: p}, success: function (arg) { console.log(arg); } }) } function addClass(cs) { var title = $(cs).parent().children().attr('title'); $.ajax({ url: '/add_class.html', type: 'POST', data: {title: title}, success: function (arg) { if (arg == '成功') { //window.location.reload(); $(cs).parent().children().attr() } else { alert(arg); } } }) } </script> </body> </html>
get_students.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <div> <a href="/add_students.html">添加</a> </div> <table border="1"> <thead> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>班级</th> <th>操作</th> </tr> </thead> <tbody> {% for row in stu_list %} <tr nid="{{ row.id }}"> <td>{{ row.id }}</td> <td>{{ row.username }}</td> <td>{{ row.age }}</td> <td> {% if row.gender == 1 %} 男 {% elif row.gender == 2 %} 女 {% elif row.gender == 3 %} 保密 {% endif %} </td> <td>{{ row.cs.title }}</td> <td> <a href="/del_student.html?nid={{ row.id }}">删除</a> | <a onclick="removeStudent(this)" href= "javascript:void(0);">Ajax删除</a> | <a href="/edit_students.html?nid={{ row.id }}">编辑</a> </td> </tr> {% endfor %} </tbody> </table> <script src="/static/jquery-3.5.1.min.js"></script> <script> function removeStudent(ths) { var nid = $(ths).parent().parent().attr('nid'); $.ajax({ url: '/ajax4.html', type: 'GET', data: {nid: nid}, success: function (arg) { if (arg == '成功') { //window.location.reload(); $(ths).parent().parent().remove() } else { alert(arg); } } }) } </script> </body> </html>
get_teachers.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <div> <a href="add_teachers.html">添加</a> <table border="1"> <thead> <tr> <th>ID</th> <th>教师姓名</th> <th>分配班级</th> <th>编辑</th> </tr> </thead> <tbody> {% for row in teacher_list %}<tr> <td>{{ row.id }}</td> <td>{{ row.name }}</td> <td> {% for obj in row.sss.all %} <span> {{ obj.title }}</span> {% endfor %} </td> <td> <a href="/edit_teachers.html?nid={{ row.id }}">编辑</a> | <a href="/del_teacher.html?nid={{ row.id }}">删除</a> | <a href="/set_classes.html?nid={{ row.id }}">分配班级</a> </td> </tr> {% endfor %} </tbody> </table> </div> </body> </html>
set_class.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <form action="/set_classes.html?nid={{ nid }}" method="POST"> <p>{{ t_obj.name }}</p> {% csrf_token %} <select multiple size="5" name="cs_ids"> {% for item in all_classes_list %} {% if item.id in id_list %} <option value="{{ item.id }}" selected="selected">{{ item.title }}</option> {% else %} <option value="{{ item.id }}">{{ item.title}}</option> {% endif %} {% endfor %} </select> <input type="submit" value="提交"> </form> </body> </html>
set_teacher.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body> <form action="/set_teacher.html?nid={{ nid }}" method="POST"> {% csrf_token %} <select multiple size="5" name="teacher_ids"> {% for item in all_teacher_list %} {% if item.id in id_list %} <option value="{{ item.id }}" selected="selected">{{ item.name }}</option> {% else %} <option value="{{ item.id }}">{{ item.name }}</option> {% endif %} {% endfor %} </select> <input type="submit" value="提交"> </form> </body> </html>
ajax.py
from django.shortcuts import render, redirect, HttpResponse def ajax1(request): return render(request, 'ajax1.html') def ajax2(request): user = request.GET.get("username") pwd = request.GET.get('password') import time time.sleep(5) return HttpResponse('我愿意') def ajax3(request): v1 = request.POST.get('v1') v2 = request.POST.get('v2') try: v3 = int(v1) + int(v2) except Exception as e: v3 = '输入格式错误' return HttpResponse(v3) from app01 import models def ajax4(request): nid = request.GET.get('nid') msg = '成功' try: models.Student.objects.filter(id=nid).delete() except Exception as e: msg = str(e) return HttpResponse(msg) def remove_class(request): nid = request.GET.get('nid') msg = '成功' try: models.Student.objects.filter(cs_id=nid).update(cs_id=10) cs_obj = models.Classes.objects.filter(id=nid).first() cs_obj.a.clear() models.Classes.objects.filter(id=nid).delete() except Exception as e: msg = str(e) return HttpResponse(msg) def add_class(request): title = request.POST.get('title') msg = '成功' try: models.Classes.objects.create(title=title) except Exception as e: msg = str(e) return HttpResponse(msg)
ajax1.html
<!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="UTF-8"> <title>Title</title> <style> .btn { display: inline-block; padding: 5px 15px; background: darkgoldenrod; color: white; cursor: pointer; } </style> </head> <body> <div> <input placeholder="用户名" type="text" id="username"/> <input placeholder="密码" type="password" id="password"/> <div class="btn" onclick="submitForm();">提交</div> </div> {#<!--#} <div> <input placeholder="数字" type="text" id="i1"/> + <input placeholder="数字" type="text" id="i2"/> <div class="btn" onclick="addForm();">=</div> <input placeholder="数字" type="text" id="i3"/> </div> {#-->#} <script src="/static/jquery-3.5.1.min.js"></script> <script> function submitForm() { var u = $('#username').val(); var p = $('#password').val(); $.ajax({ url: '/ajax2.html', type: 'GET', data: {username: u, password: p}, success: function (arg) { console.log(arg); } }) } function addForm(){ var v1 = $('#i1').val(); var v2 = $('#i2').val(); $.ajax({ url: 'ajax3.html', type: 'POST', data: {'v1':v1,'v2':v2}, success:function (arg){ //console.log(arg); $('#i3').val(arg); //通过js互动刷新页面 // window.location.reload(); } }) } </script> </body> </html>