美文网首页
Django3框架学习四:班级管理系统

Django3框架学习四:班级管理系统

作者: 丘山Ivan | 来源:发表于2020-05-06 17:11 被阅读0次

    终端中cd到当前文件路径下,输入python3 manage.py startapp app01

    项目目录结构

    手动再数据库中添加一条班级数据


    Navicat Premium 手动添加一条班级数据

    班级列表

    编写urls.py文件,

    urlpatterns = [
      # 班级
        path('class/',views.classes),
    ]
    

    app01文件夹下views.py 添加对应的班级列表函数

    # 班级列表
    import SQLHelper
    def classes(request):
        obj = SQLHelper()
        class_list = obj.get_list("select id,name from class")
        obj.close()
        return render(request, 'classes.html', {"class_list": class_list})
    

    创建班级列表页面classes.html

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>班级列表</title>
    </head>
    <body style="margin: 30px">
    <div>
        <h3>班级列表</h3>
      <a href="/addclass" >添加班级</a>
        <table class="table">
            <thead>
            <tr>
                <td>ID</td>
                <td>班级名称</td>
                <td>操作</td>
            </tr>
            </thead>
            <tbody>
            <!--   class_list 就是views.py中的 classes 函数中的class_list  -->
            <!-- 模板语言for循环 -->
            {% for class in class_list %}
                <tr>
                    <td>{{ class.id }}</td>
                    <td>{{ class.name }}</td>
                    <td>
                        <a href="\edit_class\?id={{ class.id }}" class="btn btn-info">编辑</a>
                        <a href="\delete_class\?id={{ class.id }}" class="btn btn-danger">删除</a>
                    </td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
    </body>
    </html>
    
    班级列表(丑)

    添加班级

    编写urls.py文件,

    urlpatterns = [
        path('class/',views.classes),  # 班级列表
        path('addclass/',views.add_class), #添加班级
    ]
    
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>add_class</title>
    </head>
    <body>
        <h1>添加班级</h1>
         <!-- Form表单post方式提交数据到 addclass -->
        <form action="/addclass/" method="post">
            <p>班级名称:<input type="text" name="name"></p>
           <!-- msg 错误提示信息--> 
            <p>{{ msg }}</p> 
            <input type="submit" value="提交">
        </form>
    </body>
    </html>
    

    views.py 内编写添加班级函数

    # 添加班级
    def add_class(request):
        if request.method == 'GET':
            #返回渲染添加班级页面
            return render(request, 'addclass.html')
        else:
            # 接收点击提交按钮的数据
            v = request.POST.get('name')
            if len(v) > 0:
                obj = SQLHelper()
                obj.modify("insert into class(name) values(%s)", [v, ])
                obj.close()
                return redirect('/class/')
            else:
                return render(request, 'addclass.html', {"msg": "班级名称不能为空"})
    
    
    
    添加班级

    编辑班级

    views.py中编写编辑班级函数。

    urlpatterns = [
        path('class/',views.classes),#班级列表
        path('addclass/',views.add_class),#添加班级
        path('edit_class/', views.edit_class),#编辑班级
    ]
    

    edit_class.html 编辑班级页面

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>编辑班级</title>
    </head>
    <body>
        <h1>编辑班级</h1>
        <div>
            <p>原名:{{ result.name }}</p>
        </div>
        <!-- editClass函数需要用get方式接收参数 -->
        <form action="/edit_class/?id={{ result.id }}" method="post">
        <!-- editClass函数需要用post方式接收参数 -->
        <!--  <input style="display: none" name="id" value="{{ result.id }}">#}  -->
            <p>改为:<input type="text" name="name"></p>
            <input type="submit" value="提交">
        </form>
    </body>
    </html>
    

    views.py 中添加编辑班级的函数

    # 编辑班级
    def edit_class(request):
        if request.method == "GET":
          # 从classes.html中的编辑a标签获取到的数据
            id = request.GET.get("id")
            obj = SQLHelper()
            result = obj.get_one("select id,name from class where id = %s", id)
            obj.close()
            return render(request, 'edit_class.html', {"result": result})
        else:
            id = request.GET.get("id")
            # id = request.POST.get("id")
            name = request.POST.get("name")
            obj = SQLHelper()
            obj.modify("update class set name = %s where id = %s", [name, id, ])
            obj.close()
            return redirect("/class/")
    
    编辑班级

    查看到编辑和删除对应的id的值。

    鼠标右键 - 检查 ==> 班级列表

    删除班级

    删除班级不需要专门的删除页面。暂时就点击删除按钮,直接删除掉。

    urls.py中编写删除班级函数。

    urlpatterns = [
        path('class/',views.classes),#班级列表
        path('addclass/',views.add_class),#添加班级
        path('edit_class/', views.edit_class),#编辑班级
        path('delete_class/',views.delete_class),#删除班级
    ]
    

    views.py编辑删除函数

    # 删除班级
    def delete_class(request):
        id = request.GET.get('id')
        obj = SQLHelper()
        obj.modify("delete from class where id=%s", id)
        obj.close()
        return redirect('/class/')
    

    学生和老师的HTML代码和班级的类似。直接贴其余全部代码。

    urls.py

    urlpatterns = [
        path('class/',views.classes),#班级列表
        path('addclass/',views.add_class),#添加班级
        path('edit_class/', views.edit_class),#编辑班级
        path('delete_class/',views.delete_class),#删除班级
        
        # 学生
        path('students/',views.students),
        path('addStudent/',views.addStudent),
        path('editStudent/',views.edit_student),
        path('delete_student/',views.deleteStudent),
        # 老师
        path('tearchers/',views.tearchers),
        path('addtearcher/',views.addtearchers),
        path('editTearcher/',views.editTearcher),
        path('deleteTearcher/',views.deleteTearcher),
    ]
    

    views.py

    # 学生列表
    def students(request):
        obj = SQLHelper()
        student_list = obj.get_list("select student.id,student.sname,class.name,student.cid from student left join class on student.cid = class.id",
            [])
        class_list = obj.get_list('select id,name from class', [])
        obj.close()
        return render(request, "students.html", {"student_list": student_list, 'class_list': class_list})
    
    
    # 添加学生
    def addStudent(request):
        if request.method == "GET":
            obj = SQLHelper()
            classes = obj.get_list("select id,name from class")
            obj.close()
            return render(request, "addStudent.html", {'classes': classes})
        else:
            class_id = request.POST.get("class_id")
            sname = request.POST.get("sname")
            obj = SQLHelper()
            obj.modify("insert into student( sname, cid) value (%s,%s)", [sname, class_id])
            obj.close()
            return redirect("/students/")
    
    # 删除学生
    def deleteStudent(request):
        id = request.GET.get("id")
        obj = SQLHelper()
        obj.modify("delete from student  where id = %s", id)
        obj.close()
        return redirect("/students/")
    
    # 编辑学生
    def edit_student(request):
        if request.method == "GET":
            id = request.GET.get("id")
            obj = SQLHelper()
            class_list = obj.get_list("select id,name from class", [])
            student = obj.get_one(
                "select student.id,student.sname,student.cid,class.name from student left join class on  student.cid = class.id where student.id = %s",
                id)
            obj.close()
            return render(request, "edit_student.html", {"student": student, "class_list": class_list})
        else:
            id = request.POST.get("id")
            sname = request.POST.get("sname")
            cid = request.POST.get("class_id")
            obj = SQLHelper()
            obj.modify("update student set sname = %s,cid = %s where id = %s", [sname, cid, id, ])
            obj.close()
            return redirect("/students/")
    
    ###老师列表
    def tearchers(request):
        obj = SQLHelper()
        tearcher_list = obj.get_list('''
            SELECT tearcher.tid,tearcher.tname,tearch2class.cid,class.name from tearcher  
            LEFT JOIN tearch2class on tearcher.tid = tearch2class.tid    
            LEFT JOIN class ON class.id = tearch2class.cid;
        ''', [])
        result = {}
        for tearcher in tearcher_list:
            tid = tearcher['tid']
            if tid in result:
                result[tid]['classes'].append({'cid':tearcher['cid'],'name':tearcher['name']})
            else:
                result[tid] = {
                    'tid':tearcher['tid'],
                    'tname':tearcher['tname'],
                    'classes':[{'cid':tearcher['cid'],'name':tearcher['name']}],
                }
        class_list = obj.get_list('select * from class')
        obj.close()
        return render(request, 'tearchers.html', {'result': result.values(),"class_list":class_list})
    
    
    # 添加老师
    def addtearchers(request):
        if request.method == 'GET':
            obj = SQLHelper()
            class_list = obj.get_list('select * from class')
            obj.close()
            return render(request,'addTearcher.html',{"class_list":class_list})
        else:
            tname = request.POST.get('tname')
            clds = request.POST.getlist('class_ids')
            obj = SQLHelper()
            #老师表中添加数据 #获取老师id
            tearcher_id = obj.create('insert into tearcher(tname) values (%s)', [tname])
            #老师班级表中插入数据
            sql_args = []
            for cid in clds:
                temp = (tearcher_id,cid)
                sql_args.append(temp)
            obj.multiple_modify('insert into tearch2class(tid, cid) values (%s,%s)', sql_args)
            obj.close()
            return redirect('/tearchers/')
    # 编辑老师
    def editTearcher(request):
        if request.method == 'GET':
            tid = request.GET.get('tid')
            obj = SQLHelper()
            tearcher_info = obj.get_one('select tid,tname from tearcher where tid = %s',[tid])
            tearcher_class_list = obj.get_list('select cid from tearch2class where tearch2class.tid = %s',[tid,])
            class_list = obj.get_list('select id,name from class')
            obj.close()
            temp = []
            for i in tearcher_class_list:
                temp.append(i['cid'])
            return render(request,'edit_tearcher.html',{
                'info':tearcher_info,
                'tearcher_class_list':temp,
                'class_list':class_list
            })
        else:
            tid = request.GET.get('tid')
            class_ids = request.POST.getlist('class_ids')
            tname = request.POST.get('tname')
            #更新老师表
            obj = SQLHelper()
            obj.modify('update tearcher set tname=%s where tid = %s',[tname,tid])
            #更细老师班级关系表
            # 方案一:先删除老师和班级的对应关系删除,之后再做添加
            obj.modify('delete from tearch2class where tid = %s',[tid])
            sql_args = []
            for cid in class_ids:
                temp = (tid, cid)
                sql_args.append(temp)
            obj.multiple_modify('insert into tearch2class(tid, cid) values (%s,%s)', sql_args)
            obj.close()
            # 方案二:把新的班级数据和老的数据做对比进行删除和增加
            return  redirect('/tearchers/')
      # 删除老师
    def deleteTearcher(request):
        tid = request.GET.get('tid')
        obj = SQLHelper()
        obj.modify('delete from tearcher  where tid = %s', tid)
        obj.modify('delete from tearch2class  where tid = %s', tid)
        obj.close()
        return redirect('/tearchers/')
    

    Demo地址

    相关文章

      网友评论

          本文标题:Django3框架学习四:班级管理系统

          本文链接:https://www.haomeiwen.com/subject/wxyfghtx.html