python3.6+django2.0 一小时学会开发一套学员管理系统demo

1.在pycharm中新建project demo1 添加app01 点击create按钮完成新建

2.在demo项目目录下新建目录static,并在settings.py中追加代码:

  

STATICFILES_DIRS=(os.path.join(BASE_DIR,  ‘static‘),)

  

3.在setting.py中添加模板路径:

TEMPLATES = [
    {
        ‘BACKEND‘: ‘...‘,
        ‘DIRS‘: [os.path.join(BASE_DIR,  ‘templates‘),],
        ‘APP_DIRS‘: ...,
        ‘OPTIONS‘: {
            ‘context_processors‘: [
                ...
            ],
        },
    },
]

4.学员管理系统数据库设计:

在app01/model.py目录下建立 班级、老师、学生 、老师与班级关联表  四张表:

from django.db import models

# Create your models here.

class Classes(models.Model):
    ‘‘‘
    班级表
    ‘‘‘
    title=models.CharField(max_length=32)
    a=models.ManyToManyField(‘Teachers‘)

class Teachers(models.Model):
    ‘‘‘
    老师表
    ‘‘‘
    name=models.CharField(max_length=32)

class Students(models.Model):
    username=models.CharField(max_length=32)
    age=models.IntegerField()
    gender=models.BooleanField()
    cs=models.ForeignKey(Classes,on_delete=models.CASCADE)

在终端Terminal 项目目录下执行数据表更新命令:

python manage.py makemigrations
python manage.py migrate

至此生成了四张数据表,可以在pycharm中,点开右上角的Database面板,然后将项目中templates目录下边的db.sqlite3鼠标拖拽到Database面板下,对新创建的数据表进行查看。

5.学员管理系统之班级管理:

为了方便分别操作班级、老师、学生相关的业务,将app01目录下的views.py 删掉,在app01目录下新建目录views,并在views目录下 新建classes.py teachers.py students.py。

1.在classes.py 中写 get_classes add_classes del_classes edit_classes四个函数,完成对 班级数据 的增删改查:

from django.shortcuts import render,redirect
from app01 import models

def get_classes(request):
    cls_list = models.Classes.objects.all()
    return render(request,‘get_classes.html‘,{‘cls_list‘:cls_list})

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.Classes.objects.filter(id=nid).delete()
    return redirect(‘/classes.html‘)

def edit_classes(request):
    if request.method=="GET":
        nid = request.GET.get(‘nid‘, ‘‘)
        obj=models.Classes.objects.get(id=nid)
        return render(request,‘edit_classes.html‘,{‘obj‘:obj})
    elif request.method=="POST":
        nid=request.POST.get(‘nid‘,‘‘)
        title=request.POST.get(‘xxoo‘,‘‘)
        models.Classes.objects.filter(id=nid).update(title=title)
        return redirect(‘/classes.html‘)

2.在urls.py 中配置url路由:  

from django.contrib import admin
from django.urls import path
from app01.views import classes,students,teachers

urlpatterns = [
    path(‘admin/‘, admin.site.urls),
    path(‘classes.html‘, classes.get_classes),
    path(‘add_classes.html‘, classes.add_classes),
    path(‘del_classes.html‘, classes.del_classes),
    path(‘edit_classes.html‘, classes.edit_classes),
    # path(‘teachers.html‘, teachers.get_teachers),
    # path(‘students.html‘, students.get_studernts),

]

3.在template目录下建立所需的html页面文件:

get_classes.html

DOCTYPE html>
<html lang="en">
<head>
    <style>
        tr td{ border:1px solid #000;text-align:center;}
    </style>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    <table width="300">
        <thead>
            <tr>
                <th>ID</th> <th>名称</th> <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for row in cls_list %}
            <tr>
                <td>{{ row.id }}</td>
                <td>{{ row.title }}</td>
                <td><a href="/del_classes.html?nid={{ row.id }}">删除</a>
                    |<a href="/edit_classes.html?nid={{ row.id }}">编辑</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<div><a href="/add_classes.html">添加</a> </div>
</body>
</html>

add_classes.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/add_classes.html" method="post">
    {% csrf_token %}
    <input type="text" name="title">
    <input type="submit" value="提交">
</form>
</body>
</html>

edit_classes.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" action="/edit_classes.html">
    {% csrf_token %}
    <input type="hidden" name="nid" value="{{ obj.id }}">
    <input type="text" name="xxoo" value="{{ obj.title }}">
    <input type="submit" value="提交">
</form>

</body>
</html>

  

6.学员管理系统之学员管理:

1.在students.py 中写 get_students add_students del_students edit_students 四个函数,完成对 学生数据 的增删改查:

from django.shortcuts import render,redirect
from app01 import models

def get_students(request):
    stu_list=models.Students.objects.all()
    return render(request,‘get_students.html‘,{‘stu_list‘:stu_list})

def add_students(request):
    if request.method==‘GET‘:
        cs_list=models.Classes.objects.all()
        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.Students.objects.create(
            username=u,
            age=a,
            gender=g,
            cs_id=c
        )
        return redirect(‘/students.html‘)

def del_students(request):
    nid = request.GET.get(‘nid‘, ‘‘)
    models.Students.objects.filter(id=nid).delete()
    return redirect(‘/students.html‘)

def edit_students(request):
    if request.method=="GET":
        nid = request.GET.get(‘nid‘, ‘‘)
        obj=models.Students.objects.get(id=nid)
        cs_list = models.Classes.objects.all()
        return render(request,‘edit_students.html‘,{‘obj‘:obj,‘cs_list‘:cs_list})
    elif request.method=="POST":
        nid=request.POST.get(‘nid‘,‘‘)
        u = request.POST.get(‘username‘, ‘‘)
        a = request.POST.get(‘age‘, ‘‘)
        g = request.POST.get(‘gender‘, ‘‘)
        c = request.POST.get(‘cs‘, ‘‘)
        models.Students.objects.filter(id=nid).update(
            username=u,
            age=a,
            gender=g,
            cs_id=c)
        return redirect(‘/students.html‘)

  

2.在urls.py 中配置url路由: 

from django.contrib import admin
from django.urls import path
from app01.views import classes,students,teachers

urlpatterns = [
    path(‘admin/‘, admin.site.urls),

    path(‘classes.html‘, classes.get_classes),
    path(‘add_classes.html‘, classes.add_classes),
    path(‘del_classes.html‘, classes.del_classes),
    path(‘edit_classes.html‘, classes.edit_classes),

    path(‘students.html‘, students.get_students),
    path(‘add_students.html‘, students.add_students),
    path(‘del_students.html‘, students.del_students),
    path(‘edit_students.html‘, students.edit_students),
    # path(‘teachers.html‘, teachers.get_teachers),
]

  

3.在template目录下建立所需的html页面文件:

get_students.html

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        tr td{ border:1px solid #000;text-align:center;}
    </style>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
                <th>班级</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for row in stu_list %}
            <tr>
                <td>{{ row.id }}</td>
                <td>{{ row.username }}</td>
                <td>{{ row.age }}</td>
                <td>{{ row.gender }}</td>
                <td>{{ row.cs.title }}</td>
                <td><a href="/del_students.html?nid={{ row.id }}">删除</a>
                    |<a href="/edit_students.html?nid={{ row.id }}">编辑</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<div><a href="/add_students.html">添加</a> </div>
</body>
</html>

add_students

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>添加用户</h1>
<form method="post" action="/add_students.html">
    {% csrf_token %}
    <p><input type="text" name="username" placeholder="用户名"></p>
    <p><input type="text" name="age" placeholder="年龄"></p>
    <p>
        男<input type="radio" name="gender" value="1">
        女<input type="radio" name="gender" value="0">
    </p>
    <p>
        <select name="cs">
            {% for row in cs_list %}
            <option value="{{ row.id }}">{{ row.title }}</option>
            {% endfor %}
        </select>
    </p>
    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>

edit_students.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>编辑用户</h1>
<form method="post" action="/edit_students.html">
    {% csrf_token %}
    <input type="hidden"  name="nid" value="{{ obj.id }}">
    <p><input type="text" name="username" placeholder="用户名"></p>
    <p><input type="text" name="age" placeholder="年龄"></p>
    <p>
        男<input type="radio" name="gender" value="1">
        女<input type="radio" name="gender" value="0">
    </p>
    <p>
        <select name="cs">
            {% for row in cs_list %}
            <option value="{{ row.id }}">{{ row.title }}</option>
            {% endfor %}
        </select>
    </p>
    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>

7.学员管理系统之给班级分配老师:

在teachers数据表中增加一些老师信息:

  在pycharm右上角的Database打开面板,然后将template目录下边的db.splte3鼠标拖入到Database面板中,打开db==》app01_teachers表

  点击“+”,然后填入老师信息,然后点击有“DB”标志的向上箭头,进行数据保存。

1.在classes.py中增加set_teachers函数

def set_teachers(request):
    if request.method==‘GET‘:
        nid=request.GET.get(‘nid‘,‘‘)
        cls_obj=models.Classes.objects.get(id=nid)
        cls_teacher_list=cls_obj.a.all()
        all_teacher_list=models.Teachers.objects.all()
        return render(request,‘set_teachers.html‘,{
            ‘cls_teacher_list‘:cls_teacher_list,
            ‘all_teacher_list‘:all_teacher_list,
            ‘nid‘:nid,
        })
    elif request.method==‘POST‘:
        nid = request.POST.get(‘nid‘, ‘‘)
        ids_str=request.POST.getlist(‘teacher_id‘,‘‘)
        ids_int=[]
        for i in ids_str:
            i=int(i)
            ids_int.append(i)
        obj=models.Classes.objects.get(id=nid)
        obj.a.set(ids_int)
        return redirect(‘/classes.html‘)

2.在urls.py 中配置url路由: 

from django.contrib import admin
from django.urls import path
from app01.views import classes,students,teachers

urlpatterns = [
    path(‘admin/‘, admin.site.urls),

    path(‘classes.html‘, classes.get_classes),
    path(‘add_classes.html‘, classes.add_classes),
    path(‘del_classes.html‘, classes.del_classes),
    path(‘edit_classes.html‘, classes.edit_classes),

    path(‘students.html‘, students.get_students),
    path(‘add_students.html‘, students.add_students),
    path(‘del_students.html‘, students.del_students),
    path(‘edit_students.html‘, students.edit_students),

    path(‘set_teachers.html‘, classes.set_teachers),
]

  

3.在template目录下建立所需的html页面文件:

set_teachers.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/set_teachers.html" method="post">
    <input type="hidden" name="nid" value="{{ nid }}">
    {% csrf_token %}
    <select multiple size="10" name="teacher_id">

        {% for item in all_teacher_list %}
            {% if item in cls_teacher_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>

对get_classes.html进行增添修改为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th> <th>名称</th> <th>任课老师</th> <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for row in cls_list %}
            <tr>
                <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 href="/edit_classes.html?nid={{ row.id }}">编辑</a>
                    |<a href="/set_teachers.html?nid={{ row.id }}">分配老师</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<div><a href="/add_classes.html">添加</a> </div>
</body>
</html>

8.初识Ajax

Ajax是异步传输方式,偷偷的向后台发请求,不引起页面刷新,下面通过一个小例子来认识Ajax这种数据传输方式。

首先下载jQuery导入项目下的static目录下

1.在app01/Views目录下新建ajax.py

from django.shortcuts import render,redirect,HttpResponse

def ajax1(request):
    return render(request,‘ajax1.html‘)

def ajax2(request):
    u=request.GET.get(‘username‘)
    p=request.GET.get(‘password‘)
    return HttpResponse(‘我愿意‘)

2.在urls.py中配置相关路由

from django.contrib import admin
from django.urls import path
from app01.views import classes,students,teachers,ajax

urlpatterns = [
    path(‘admin/‘, admin.site.urls),

    path(‘classes.html‘, classes.get_classes),
    path(‘add_classes.html‘, classes.add_classes),
    path(‘del_classes.html‘, classes.del_classes),
    path(‘edit_classes.html‘, classes.edit_classes),

    path(‘students.html‘, students.get_students),
    path(‘add_students.html‘, students.add_students),
    path(‘del_students.html‘, students.del_students),
    path(‘edit_students.html‘, students.edit_students),

    path(‘set_teachers.html‘, classes.set_teachers),

    path(‘ajax1.html‘, ajax.ajax1),
    path(‘ajax2.html‘, ajax.ajax2),
]

3.在template目录下新建ajax1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .btn{
            display: inline-block;
            padding: 5px 15px;
            background-color: coral;
            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>
<script src="/static/jquery-3.3.1.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) {
                //回调函数 arg是服务器返回的字符串
                console.log(arg)
            }

        })

    }
</script>
</body>

</html>

9.学员管理系统之Ajax删除学员:

1.在ajax.py中增加ajax4函数

from app01 import models

def ajax4(request):
    nid=request.GET.get(‘nid‘)
    msg=‘成功‘
    try:
        models.Students.objects.get(id=nid).delete()
    except Exception as e:
        msg=str(e)
    return HttpResponse(msg)

2.在urls.py中配置相关路由

from django.contrib import admin
from django.urls import path
from app01.views import classes,students,teachers,ajax

urlpatterns = [
    path(‘admin/‘, admin.site.urls),

    path(‘classes.html‘, classes.get_classes),
    path(‘add_classes.html‘, classes.add_classes),
    path(‘del_classes.html‘, classes.del_classes),
    path(‘edit_classes.html‘, classes.edit_classes),

    path(‘students.html‘, students.get_students),
    path(‘add_students.html‘, students.add_students),
    path(‘del_students.html‘, students.del_students),
    path(‘edit_students.html‘, students.edit_students),

    path(‘set_teachers.html‘, classes.set_teachers),

    path(‘ajax1.html‘, ajax.ajax1),
    path(‘ajax2.html‘, ajax.ajax2),
    path(‘ajax4.html‘, ajax.ajax4),
]

3.对get_students.html进行添加修改:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<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>{{ row.gender }}</td>
                <td>{{ row.cs.title }}</td>
                <td><a href="/del_students.html?nid={{ row.id }}">删除</a>
                    |<a onclick="removeStudent(this);" href="#">Ajax删除</a>
                    |<a href="/edit_students.html?nid={{ row.id }}">编辑</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<div><a href="/add_students.html">添加</a> </div>
</body>
<script src="/static/jquery-3.3.1.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();
                }else{
                    alert(arg);
                }
            }
        })
    }
</script>
</html>

  

原文地址:https://www.cnblogs.com/xuepangzi/p/8493853.html

时间: 2024-10-03 20:52:00

python3.6+django2.0 一小时学会开发一套学员管理系统demo的相关文章

【python3】 django2.0 在生成数据库表时报错: TypeError: __init__() missing 1 required positional argument: &#39;on_delete&#39;

python: 3.6.4 django: 2.0 models.py 代码如下 # coding: utf-8 from django.db import models from django.contrib.auth.models import User # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) class Tag(models.Model)

python3.5+django2.0快速入门(一)

因为这篇教程需要用到anaconda的一些操作,如果还不懂anaconda的操作的同学可以看下这篇文章python 入门学习之anaconda篇. 创建python3+的开发环境 直接在终端输入:conda create -n newenv python=3.5 进入我们新建的开发环境newenv linux: source activate newenv window: activate newenv 安装django2.0 直接在终端输入: pip install django ,然后系统会

【Python3.6+Django2.0+Xadmin2.0系列教程一】环境搭建及项目创建

由于工作需要,接触了大半年时间的Django+xadmin框架,一直没空对这块对进行相关的梳理.最近在同事的怂恿下,就在这分享下笔者的学习及工作经验吧. 好了,话不多说,下面开始进入正题: 环境需求: 笔者的工作系统环境:Mac 10.13.4+Python3.6.x+Django2.0.x+Xadmin2.0 因此本系列教程均是以此组合为基础展开讲解.其他系统版本也基本适用,有小部分不兼容之处请自行测试. 一.Django及xadmin安装 可以使用pip命令进行安装,或者直接下载安装包用py

CentOS + Python3.6+ Django2.0 + uwsgi + nginx + mysql web发布环境搭建

目录: CentOS上升级Python 安装easy_install和pip uwsgi安装及测试 Django安装及测试 连接uwsgi与Django nginx安装及测试 连接uwsgi与nginx 连接uwsgi与Django与nginx uwsgi ini mysql安装设置 python3 Django mysql连接及测试 快速搭建blog测试 Pycharm开发 如果只是想学习django开发直接用django本身自带的开发用服务器即可. 1. CentOS上升级Python 用的

Scrapy1.4爬取笑话网站数据,Python3.5+Django2.0构建笑话应用

Part1:需求简要描述 1.抓取http://www.jokeji.cn网站的笑话 2.以瀑布流方式显示 Part2:安装爬虫框架Scrapy1.4 1. 安装Scrapy1.4 E:\django\myProject001>pip install scrapy 执行报错: error: Unable to find vcvarsall.bat Failed building wheel for Twisted 2.安装wheel E:\django\myProject001>pip ins

mysql开发简单的学员管理系统

主题:学员管理系统 需求: 用户角色,讲师\学员, 用户登陆后根据角色不同,能做的事情不同,分别如下 讲师视图 管理班级,可创建班级,根据学员qq号把学员加入班级 可创建指定班级的上课纪录,注意一节上课纪录对应多条学员的上课纪录, 即每节课都有整班学员上, 为了纪录每位学员的学习成绩,需在创建每节上课纪录是,同时 为这个班的每位学员创建一条上课纪录 为学员批改成绩, 一条一条的手动修改成绩 学员视图 提交作业 查看作业成绩 一个学员可以同时属于多个班级,就像报了Linux的同时也可以报名Pyth

Django2.0.3如何实现页面静态化

我们在开发新闻系统的时候,为了提高系统的响应速度,通常我们会将常用的数据实现静态化,我们如何将新闻内容实现静态化呢?环境:Python3.5 + Django2.0.3 引入模块: from django.shortcuts import renderfrom .models import Category,Tag,Item,Ad,Articleimport osfrom django.conf import settingsimport codecsfrom django.template.l

Django2.0.1在线教育零基础到上线教程(一)

网上这么多关于这个课程的博客,为什么还需要我自己去写一遍? 我希望你看到这篇博客,也能照我这样去写一遍博客   因为这个课程反反复复学习了几遍 都没有从头到尾完整学习过一遍 . 我想通过博客去督促以及记录学习的进度! 废话不多说, 开始第一章吧! 坦白说,这个项目坑还是挺多的吧 配置环境: Python3.x + Django2.0.1 对应仓库Mxonline3 课程介绍: 第一章:项目介绍和课程介绍 Django是一个Python中Web开发的主流框架,被许多大型公司使用,如Google,豆

Android开发工程师文集-1 小时学会Widget小组件开发

前言 大家好,给大家带来Android开发工程师文集-1 小时学会Widget小组件开发的概述,希望你们喜欢 学会用Widget (小组件) Widget小组件很方便,很快捷,可以个性化,自己定制,相关功能,可以实时更新最新内容. Widget布局,Widget配置,AppWidgetProvider与Configuration Activity Android Widget xml布局类型:AppWidget Provider <appwidget-provider xmlns:android