基于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\d+)/$', student_modify, name='modify'),
    url(r'^addstu/$', student_add, name='addstu'),
    url(r'^delstu/(?P\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 %}




    
    
    
    
    
    
    




    
    
    
    

学员查询及管理

{% for stu in students %} {% endfor %}
姓名 学号 电话 编辑 删除
{{ stu.s_name }} {{ stu.s_id }} {{ stu.s_phone }}

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





    
    修改学员信息-{{ stu.s_name }}
    
	


{% csrf_token %}

修改学员信息-{{ stu.s_name }} 请输入修改后的信息.

 

你可能感兴趣的:(基于django的学员管理系统)