Django实现学员管理系统


Posted in Python onFebruary 26, 2019

本文实例为大家分享了Django实现学员管理系统的具体代码,供大家参考,具体内容如下

要求:实现数据的增删改查功能,并同步至数据库中。此项目实现了前端以及后端的结合。

(1) 先在settings里配置static(存放的是css样式、js代码、以及imgs),可以加在文件末尾

STATIC_URL = '/static/'
STATICFILES_DIRS = [
 os.path.join(BASE_DIR, 'static')
]

(2) 首先,新建一个django项目,在项目下的urls.py文件里,配置跳转路由,跳转到首页

urls.py

from django.conf.urls import url, include
from django.contrib import admin
 
urlpatterns = [
 url(r'^admin/', admin.site.urls),
 url(r'^student/', include('student.urls'))
]

(3) 通过python manage.py startapp student命令创建一个student的app(不要忘记在settings中配置一下),并在models.py下执行mysql操作,在这里我们就直接在数据库里手动创建表,不再使用sql语句创建表了

models.py

import pymysql
# Create your models here.
 
# 管理数据库
class DBManager(object):
 
 @classmethod
 def open_sql(cls):
  conn = pymysql.connect(
   host='127.0.0.1',
   port=3306,
   db='students',
   user='root',
   password='123456',
   use_unicode=True,
   charset='utf8'
  )
  DBManager.conn = conn
  DBManager.cursor = conn.cursor()
 
 @classmethod
 def close_sql(cls):
  DBManager.conn.commit()
  DBManager.cursor.close()
  DBManager.conn.close()
 
# 数据模型类
class StudnetModel(object):
 
 def __init__(self, s_id, s_name, s_phone):
  self.s_id = s_id
  self.s_name = s_name
  self.s_phone = s_phone
  self.table = 'students'
 
 def save(self):
  """
  保存数据模型到数据库
  :return: False 表示数据已存在 True表示保存数据成功
  """
  DBManager.open_sql()
  # 如果s_id已存在,说明学号已存在
  sql = f'SELECT * FROM students WHERE s_id={self.s_id}'
  if DBManager.cursor.execute(sql) > 0:
   # 数据已存在,插入失败
   return False
  else:
   # 插入数据
   sql = 'INSERT INTO students(s_id,s_name,s_phone)VALUES(%s,%s,%s)'
   DBManager.cursor.execute(sql,(self.s_id, self.s_name, self.s_phone))
   DBManager.close_sql()
   return True
 
 @classmethod
 def delete(cls, s_id):
  """
  根据s_id删除数据
  :param s_id: 要删除数据的id
  :return: False表示该数据不存在 True删除成功
  """
  DBManager.open_sql()
 
  # 删除的sql语句
  sql = f'DELETE FROM students WHERE s_id={s_id}'
  DBManager.cursor.execute(sql)
 
  # rowcount 执行sql语句 影响的数据条数
  if DBManager.cursor.rowcount > 0:
   DBManager.close_sql()
 
   return True
  else:
   return False
 
 @classmethod
 def object_with_id(cls, s_id):
 
  DBManager.open_sql()
  sql = f'SELECT * FROM students WHERE s_id={s_id}'
  DBManager.cursor.execute(sql)
  # 取出拿到的数据
  result = DBManager.cursor.fetchone()
  DBManager.close_sql()
  if result:
   # 返回StudentModel对象
   return cls(result[0], result[1], result[2], )
 
 def modify(self):
 
  DBManager.open_sql()
 
  sql = f"UPDATE students SET s_name='{self.s_name}' , s_phone='{self.s_phone}' WHERE s_id={self.s_id}"
 
  DBManager.cursor.execute(sql)
  if DBManager.cursor.rowcount > 0:
   DBManager.close_sql()
   return True
  else:
   return False
 
 @classmethod
 def objects(cls):
  # 只要调用该函数,返回数据库中所有的数据
  DBManager.open_sql()
  sql = 'SELECT * FROM students'
  DBManager.cursor.execute(sql)
  # 取出查询的所有数据,results是一个大元组
  results = DBManager.cursor.fetchall()
  # 将results中每一个小元组转换为StudentModel对象
  students = map(lambda t:cls(t[0], t[1], t[2]), results)
  # 关闭数据库
  DBManager.close_sql()
 
  return students
 
if __name__ == '__main__':
 
 StudnetModel.objects()

(4) 接下来在自己新建的app下,再手动创建一个urls.py文件,用来配置具体路由,并在views.py文件里实现视图函数(存放具体的增删改查功能的函数)

student/urls.py

from django.conf.urls import url
from .views import *
 
urlpatterns = [
 url(r'^$', student_index, name='stu_index'),
 url(r'^modify/(?P<s_id>\d+)/$', student_modify, name='modify'),
 url(r'^addstu/$', student_add, name='addstu'),
 url(r'^delstu/(?P<s_id>\d+)/$', student_del, name='delstu'),
]

student/views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
 
from .models import StudnetModel
# Create your views here.
 
def student_index(reqeust):
 
 # 取出数据库中所有的数据
 students = StudnetModel.objects()
 
 return render(reqeust, 'index.html', {'students': students})
 
 
def student_add(request):
 
 if request.method == 'POST':
 
  # 取出数据
  s_id = request.POST.get('id', None)
  s_name = request.POST.get('name', None)
  s_phone = request.POST.get('phone', None)
 
  if s_id and s_name and s_phone:
   try:
    int(s_id)
   except Exception as e:
    return HttpResponse('id必须是纯数字!')
   # 创建数据模型对象
   stu = StudnetModel(s_id, s_name, s_phone)
   # 保存数据
   if stu.save():
    # 重定向到首页
    return redirect('/student')
   else:
    # 返回提示信息
    return HttpResponse('该学号已存在!')
  else:
   return HttpResponse('添加信息不能为空!')
 else:
  # 其他访问方式,重定向到主页
  return redirect('/student')
 
 
def student_del(request, s_id):
 
 if request.method == 'GET':
  # MTV设计模式
  # 根据id判断是否存在
 
  if StudnetModel.delete(s_id):
   # 删除成功
   return redirect('/student')
  else:
   # 删除数据不存在
   return HttpResponse('要删除的数据不存在!')
 
 
def student_modify(request, s_id):
 
 if request.method == 'GET':
 
  # 根据s_id 查询这个id对应的信息
  stu = StudnetModel.object_with_id(s_id)
  if stu:
   return render(request, 'modify.html', {'stu': stu})
  else:
 
   return HttpResponse('要修改的学员id不存在!!')
 elif request.method == 'POST':
 
  # 取出修改后的参数
  s_name = request.POST.get('name')
  s_phone = request.POST.get('phone')
  stu = StudnetModel(s_id, s_name, s_phone)
  if stu.modify():
 
   return redirect('/student')
  else:
 
   return HttpResponse('修改失败,请稍后重试!')

(5) 最后就是在html代码中实现路由跳转,实现功能

首页html,index.html

{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
 
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
 <meta name="author" content="bais">
 <title></title>
 <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
 <style>
  .navbar {
   border-radius: 0px;
   margin-bottom: 0;
  }
  
  .titleContent {
   background-color: #eeeeee;
  }
  
  .mToolbar {
   padding-top: 10px;
   padding-bottom: 10px;
  }
  
  .container-fluid {
   padding-left: 8vw;
  }
  
  @media (max-width:768px) {
   .container-fluid {
    padding-left: 15px;
   }
  }
 
  .form-horizontal .control-label{
   text-align: left;
  }
 </style>
</head>
 
<body>
 
 <!--
  导航
 -->
 <nav class="navbar navbar-inverse" role="navigation">
  <div class="container-fluid">
   <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-collapse">
   <span class="sr-only">切换导航</span>
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
  </button>
    <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >学员管理系统</a>
   </div>
   <div class="collapse navbar-collapse" id="example-navbar-collapse">
    <ul class="nav navbar-nav">
     <li class=""><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页</a></li>
     <li class="active"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >学员</a></li>
 
    </ul>
 
    <ul class="nav navbar-nav navbar-right">
     <li>
      <a href="#"></span> XXX<b class="caret"></b></a>
     </li>
     <li>
      <a href="#"></span> 退出</a>
     </li>
    </ul>
 
   </div>
  </div>
 </nav>
 <!--
  标题
 -->
 <div class="container-fluid titleContent">
  <h1>学员查询及管理</h1>
 </div>
 <!--
  工具栏部分 按钮
 -->
 <div class="container-fluid mToolbar">
  <button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">添加</button>
 
 </div>
 
 <!--
  模态框:搜索按钮绑定的模态框
 -->
 <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
   <div class="modal-content">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
     <h4 class="modal-title" id="myModalLabel">搜索条件</h4>
    </div>
    <div class="modal-body">
     <!--
      添加模态框中的表单
     -->
 
     <form class="form-horizontal" role="form" action="{% url 'addstu' %}" method="post">
      <div class="form-group">
       <label for="firstname" class="col-sm-2 control-label">姓名</label>
       <div class="col-sm-4">
        <input type="text" class="form-control" id="firstname" name="name" placeholder="学员姓名">
       </div>
      </div>
      <div class="form-group">
       <label for="lastname" class="col-sm-2 control-label">学号</label>
       <div class="col-sm-4">
        <input type="text" class="form-control" id="lastname" name="id" placeholder="学员学号">
       </div>
      </div>
      {% csrf_token %}
      <div class="form-group">
       <label for="lastname" class="col-sm-2 control-label">电话</label>
       <div class="col-sm-7">
        <input type="text" class="form-control" id="lastname" name="phone" placeholder="电话号码">
       </div>
      </div>
 
      <div class="modal-footer">
     <button type="submit" class="btn btn-success">提交</button>
    </div>
      
     </form>
 
 
 
    </div>
 
   </div>
   <!-- /.modal-content -->
  </div>
  <!-- /.modal -->
 </div>
 
 <!--
  表格
 -->
 <div class="container-fluid">
  <div class="table-responsive ">
   <table class="table table-bordered table-condensed">
    <thead>
     <tr class="active">
      <th>姓名</th>
      <th>学号</th>
      <th>电话</th>
      <th>编辑</th>
      <th>删除</th>
      <tbody>
       {% for stu in students %}
       <tr>
        <td>{{ stu.s_name }}</td>
        <td>{{ stu.s_id }}</td>
        <td>{{ stu.s_phone }}</td>
 
        <td><a href="{% url 'modify' stu.s_id %}" rel="external nofollow" ><span class="glyphicon glyphicon-edit"></span></a></td>
 
        <td><a href="{% url 'delstu' stu.s_id %}" rel="external nofollow" ><span class="glyphicon glyphicon-remove"></span></a></td>
       </tr>
       {% endfor %}
      </tbody>
     </tr>
    </thead>
   </table>
  </div>
 </div>
 
 
 
 <script src="{% static 'js/jquery-3.1.1.js' %}"></script>
 <script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
 
</html>

增加 / 修改学员页面,modif.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>修改学员信息-{{ stu.s_name }}</title>
 <link rel="stylesheet" href="style.css" >
 <style>
 .smart-green {
 margin-left: auto;
 margin-right: auto;
 max-width: 500px;
 background: #F8F8F8;
 padding: 30px 30px 20px 30px;
 font: 12px Arial, Helvetica, sans-serif;
 color: #666;
 border-radius: 5px;
 -webkit-border-radius: 5px;
 -moz-border-radius: 5px;
 }
 
 .smart-green h1 {
 font: 24px "Trebuchet MS", Arial, Helvetica, sans-serif;
 padding: 20px 0px 20px 40px;
 display: block;
 margin: -30px -30px 10px -30px;
 color: #FFF;
 background: #9DC45F;
 text-shadow: 1px 1px 1px #949494;
 border-radius: 5px 5px 0px 0px;
 -webkit-border-radius: 5px 5px 0px 0px;
 -moz-border-radius: 5px 5px 0px 0px;
 border-bottom: 1px solid #89AF4C;
 }
 
 .smart-green h1 > span {
 display: block;
 font-size: 11px;
 color: #FFF;
 }
 
 .smart-green label {
 display: block;
 margin: 0px 0px 5px;
 }
 
 .smart-green label > span {
 float: left;
 margin-top: 10px;
 color: #5E5E5E;
 }
 
 .smart-green input[type="text"], .smart-green input[type="email"], .smart-green textarea, .smart-green select {
 color: #555;
 height: 30px;
 line-height: 15px;
 width: 100%;
 padding: 0px 0px 0px 10px;
 margin-top: 2px;
 border: 1px solid #E5E5E5;
 background: #FBFBFB;
 outline: 0;
 -webkit-box-shadow: inset 1px 1px 2px rgba(238, 238, 238, 0.2);
 box-shadow: inset 1px 1px 2px rgba(238, 238, 238, 0.2);
 font: normal 14px/14px Arial, Helvetica, sans-serif;
 }
 
 .smart-green textarea {
 height: 100px;
 padding-top: 10px;
 }
 
 
 .smart-green .button {
 background-color: #9DC45F;
 border-radius: 5px;
 -webkit-border-radius: 5px;
 -moz-border-border-radius: 5px;
 border: none;
 padding: 10px 25px 10px 25px;
 color: #FFF;
 text-shadow: 1px 1px 1px #949494;
 }
 
 .smart-green .button:hover {
 background-color: #80A24A;
 }
 
 .error-msg{
 color: red;
 margin-top: 10px;
 }
 .success-msg{
 color: #80A24A;
 margin-top: 10px;
 margin-bottom: 10px;
 }
 </style>
</head>
<body>
<form action="{% url 'modify' stu.s_id %}" method="post" class="smart-green">
 {% csrf_token %}
 <h1>修改学员信息-{{ stu.s_name }}
  <span>请输入修改后的信息.</span>
 </h1>
 <label>
  <span>姓名 :</span>
  <input id="name" type="text" name="name" class="error" placeholder="请输入修改后姓名" value="{{ stu.s_name }}">
  <div class="error-msg"></div>
 </label>
 
 <label>
  <span>电话 :</span>
  <input id="email" type="text" value="{{ stu.s_phone }}" name="phone" placeholder="请输入修改后的电话"/>
  <div class="error-msg"></div>
 </label>
 <label>
  <span> </span>
  <input type="submit" class="button" value="提交"/>
 </label>
 
</form>
 
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现百度关键词排名查询
Mar 30 Python
python中pandas.DataFrame排除特定行方法示例
Mar 12 Python
python代码实现ID3决策树算法
Dec 20 Python
Python字符串格式化%s%d%f详解
Feb 02 Python
python docx 中文字体设置的操作方法
May 08 Python
Python构建图像分类识别器的方法
Jan 12 Python
python脚本执行CMD命令并返回结果的例子
Aug 14 Python
Django模板语言 Tags使用详解
Sep 09 Python
python使用socket实现的传输demo示例【基于TCP协议】
Sep 24 Python
查看端口并杀进程python脚本代码
Dec 17 Python
使用OpenCV去除面积较小的连通域
Jul 05 Python
Python tkinter之Bind(绑定事件)的使用示例
Feb 05 Python
Python实现读取txt文件中的数据并绘制出图形操作示例
Feb 26 #Python
Django实现学生管理系统
Feb 26 #Python
python爬取微信公众号文章的方法
Feb 26 #Python
python下载微信公众号相关文章
Feb 26 #Python
python处理DICOM并计算三维模型体积
Feb 26 #Python
学习python可以干什么
Feb 26 #Python
Python3几个常见问题的处理方法
Feb 26 #Python
You might like
php 友好URL的实现(吐血推荐)
2008/10/04 PHP
PHP运行环境配置与开发环境的配置(图文教程)
2013/06/04 PHP
php之curl实现http与https请求的方法
2014/10/21 PHP
CI框架出现mysql数据库连接资源无法释放的解决方法
2016/05/17 PHP
Thinkphp5框架实现获取数据库数据到视图的方法
2019/08/14 PHP
把textarea中字符串里含有的回车换行替换成&amp;lt;br&amp;gt;的javascript代码
2007/04/20 Javascript
JS 文字符串转换unicode编码函数
2009/05/30 Javascript
js时间比较示例分享(日期比较)
2014/03/05 Javascript
浅析JavaScript基本类型与引用类型
2014/05/28 Javascript
js模仿php中strtotime()与date()函数实现方法
2015/08/11 Javascript
项目实践一图片上传之form表单还是base64前端图片压缩(前端图片压缩)
2016/07/28 Javascript
Angularjs在初始化未完毕时出现闪烁问题的解决方法分析
2016/08/05 Javascript
Node.js学习入门
2017/01/03 Javascript
Angularjs单选框相关的示例代码
2017/08/17 Javascript
HTML5+JS+JQuery+ECharts实现异步加载问题
2017/12/16 jQuery
Vue路由钩子之afterEach beforeEach的区别详解
2018/07/15 Javascript
JS常用排序方法实例代码解析
2020/03/03 Javascript
vue 导航守卫和axios拦截器有哪些区别
2020/12/19 Vue.js
编写Python脚本把sqlAlchemy对象转换成dict的教程
2015/05/29 Python
Python 使用requests模块发送GET和POST请求的实现代码
2016/09/21 Python
python字符串,数值计算
2016/10/05 Python
python 与GO中操作slice,list的方式实例代码
2017/03/20 Python
Python抓取框架Scrapy爬虫入门:页面提取
2017/12/01 Python
python并发编程之线程实例解析
2017/12/27 Python
python表格存取的方法
2018/03/07 Python
Python在图片中插入大量文字并且自动换行
2019/01/02 Python
python suds访问webservice服务实现
2020/06/26 Python
CSS3教程(2):网页边框半径和网页圆角
2009/04/02 HTML / CSS
使用HTML5拍照示例代码
2013/08/06 HTML / CSS
AVIS安飞士奥地利租车官网:提供奥地利、欧洲和全世界汽车租赁
2016/11/29 全球购物
美国著名手表网站:Timepiece
2017/11/15 全球购物
Shopee菲律宾:在线购买和出售
2019/11/25 全球购物
2015年发展党员工作总结报告
2015/03/31 职场文书
基于Python的EasyGUI学习实践
2021/05/07 Python
Python制作表白爱心合集
2022/01/22 Python
mysql字段为NULL索引是否会失效实例详解
2022/05/30 MySQL