Django實(shí)現(xiàn)學(xué)員管理系統(tǒng)
本文實(shí)例為大家分享了Django實(shí)現(xiàn)學(xué)員管理系統(tǒng)的具體代碼,供大家參考,具體內(nèi)容如下
要求:實(shí)現(xiàn)數(shù)據(jù)的增刪改查功能,并同步至數(shù)據(jù)庫(kù)中。此項(xiàng)目實(shí)現(xiàn)了前端以及后端的結(jié)合。
(1) 先在settings里配置static(存放的是css樣式、js代碼、以及imgs),可以加在文件末尾
STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ]
(2) 首先,新建一個(gè)django項(xiàng)目,在項(xiàng)目下的urls.py文件里,配置跳轉(zhuǎn)路由,跳轉(zhuǎn)到首頁(yè)
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) 通過(guò)python manage.py startapp student命令創(chuàng)建一個(gè)student的app(不要忘記在settings中配置一下),并在models.py下執(zhí)行mysql操作,在這里我們就直接在數(shù)據(jù)庫(kù)里手動(dòng)創(chuàng)建表,不再使用sql語(yǔ)句創(chuàng)建表了
models.py
import pymysql # Create your models here. # 管理數(shù)據(jù)庫(kù) 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() # 數(shù)據(jù)模型類 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): """ 保存數(shù)據(jù)模型到數(shù)據(jù)庫(kù) :return: False 表示數(shù)據(jù)已存在 True表示保存數(shù)據(jù)成功 """ DBManager.open_sql() # 如果s_id已存在,說(shuō)明學(xué)號(hào)已存在 sql = f'SELECT * FROM students WHERE s_id={self.s_id}' if DBManager.cursor.execute(sql) > 0: # 數(shù)據(jù)已存在,插入失敗 return False else: # 插入數(shù)據(jù) 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): """ 根據(jù)s_id刪除數(shù)據(jù) :param s_id: 要?jiǎng)h除數(shù)據(jù)的id :return: False表示該數(shù)據(jù)不存在 True刪除成功 """ DBManager.open_sql() # 刪除的sql語(yǔ)句 sql = f'DELETE FROM students WHERE s_id={s_id}' DBManager.cursor.execute(sql) # rowcount 執(zhí)行sql語(yǔ)句 影響的數(shù)據(jù)條數(shù) 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) # 取出拿到的數(shù)據(jù) result = DBManager.cursor.fetchone() DBManager.close_sql() if result: # 返回StudentModel對(duì)象 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): # 只要調(diào)用該函數(shù),返回?cái)?shù)據(jù)庫(kù)中所有的數(shù)據(jù) DBManager.open_sql() sql = 'SELECT * FROM students' DBManager.cursor.execute(sql) # 取出查詢的所有數(shù)據(jù),results是一個(gè)大元組 results = DBManager.cursor.fetchall() # 將results中每一個(gè)小元組轉(zhuǎn)換為StudentModel對(duì)象 students = map(lambda t:cls(t[0], t[1], t[2]), results) # 關(guān)閉數(shù)據(jù)庫(kù) DBManager.close_sql() return students if __name__ == '__main__': StudnetModel.objects()
(4) 接下來(lái)在自己新建的app下,再手動(dòng)創(chuàng)建一個(gè)urls.py文件,用來(lái)配置具體路由,并在views.py文件里實(shí)現(xiàn)視圖函數(shù)(存放具體的增刪改查功能的函數(shù))
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): # 取出數(shù)據(jù)庫(kù)中所有的數(shù)據(jù) students = StudnetModel.objects() return render(reqeust, 'index.html', {'students': students}) def student_add(request): if request.method == 'POST': # 取出數(shù)據(jù) 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必須是純數(shù)字!') # 創(chuàng)建數(shù)據(jù)模型對(duì)象 stu = StudnetModel(s_id, s_name, s_phone) # 保存數(shù)據(jù) if stu.save(): # 重定向到首頁(yè) return redirect('/student') else: # 返回提示信息 return HttpResponse('該學(xué)號(hào)已存在!') else: return HttpResponse('添加信息不能為空!') else: # 其他訪問(wèn)方式,重定向到主頁(yè) return redirect('/student') def student_del(request, s_id): if request.method == 'GET': # MTV設(shè)計(jì)模式 # 根據(jù)id判斷是否存在 if StudnetModel.delete(s_id): # 刪除成功 return redirect('/student') else: # 刪除數(shù)據(jù)不存在 return HttpResponse('要?jiǎng)h除的數(shù)據(jù)不存在!') def student_modify(request, s_id): if request.method == 'GET': # 根據(jù)s_id 查詢這個(gè)id對(duì)應(yīng)的信息 stu = StudnetModel.object_with_id(s_id) if stu: return render(request, 'modify.html', {'stu': stu}) else: return HttpResponse('要修改的學(xué)員id不存在??!') elif request.method == 'POST': # 取出修改后的參數(shù) 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('修改失敗,請(qǐng)稍后重試!')
(5) 最后就是在html代碼中實(shí)現(xiàn)路由跳轉(zhuǎn),實(shí)現(xiàn)功能
首頁(yè)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> <!-- 導(dǎo)航 --> <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">切換導(dǎo)航</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" >學(xué)員管理系統(tǒng)</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" >首頁(yè)</a></li> <li class="active"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >學(xué)員</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> <!-- 標(biāo)題 --> <div class="container-fluid titleContent"> <h1>學(xué)員查詢及管理</h1> </div> <!-- 工具欄部分 按鈕 --> <div class="container-fluid mToolbar"> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">添加</button> </div> <!-- 模態(tài)框:搜索按鈕綁定的模態(tài)框 --> <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"> <!-- 添加模態(tài)框中的表單 --> <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="學(xué)員姓名"> </div> </div> <div class="form-group"> <label for="lastname" class="col-sm-2 control-label">學(xué)號(hào)</label> <div class="col-sm-4"> <input type="text" class="form-control" id="lastname" name="id" placeholder="學(xué)員學(xué)號(hào)"> </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="電話號(hào)碼"> </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>學(xué)號(hào)</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>
增加 / 修改學(xué)員頁(yè)面,modif.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>修改學(xué)員信息-{{ 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>修改學(xué)員信息-{{ stu.s_name }} <span>請(qǐng)輸入修改后的信息.</span> </h1> <label> <span>姓名 :</span> <input id="name" type="text" name="name" class="error" placeholder="請(qǐng)輸入修改后姓名" 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="請(qǐng)輸入修改后的電話"/> <div class="error-msg"></div> </label> <label> <span> </span> <input type="submit" class="button" value="提交"/> </label> </form> </body> </html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python3+django2開(kāi)發(fā)一個(gè)簡(jiǎn)單的人員管理系統(tǒng)過(guò)程詳解
- Django實(shí)現(xiàn)學(xué)生管理系統(tǒng)
- django認(rèn)證系統(tǒng)實(shí)現(xiàn)自定義權(quán)限管理的方法
- python3.6+django2.0開(kāi)發(fā)一套學(xué)員管理系統(tǒng)
- Django admin實(shí)現(xiàn)圖書(shū)管理系統(tǒng)菜鳥(niǎo)級(jí)教程完整實(shí)例
- 基于 Django 的手機(jī)管理系統(tǒng)實(shí)現(xiàn)過(guò)程詳解
相關(guān)文章
Python3搭建http服務(wù)器的實(shí)現(xiàn)代碼
這篇文章主要介紹了Python3搭建http服務(wù)器的實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02Python Django Cookie 簡(jiǎn)單用法解析
這篇文章主要介紹了Python Django Cookie 簡(jiǎn)單用法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08tensorflow 限制顯存大小的實(shí)現(xiàn)
今天小編就為大家分享一篇tensorflow 限制顯存大小的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02python?playwright?庫(kù)上傳和下載操作(自動(dòng)化測(cè)試?playwright)
這篇文章主要介紹了python?playwright?庫(kù)上傳和下載操作(自動(dòng)化測(cè)試?playwright?),playwright中的上傳和下載比selenium的上傳和下載要簡(jiǎn)便些,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05手把手教你使用Python創(chuàng)建微信機(jī)器人
微信,一個(gè)日活10億的超級(jí)app,不僅在國(guó)內(nèi)社交獨(dú)領(lǐng)風(fēng)騷,在國(guó)外社交也同樣占有一席之地,今天我們要將便是如何用Python來(lái)生成一個(gè)微信機(jī)器人,感興趣的朋友跟隨小編一起看看吧2019-04-04