作者主页:编程指南针
作者简介:Java领域优质创作者、CSDN博客专家 、掘金特邀作者、多年架构师设计经验、腾讯课堂常驻讲师
主要内容:Java项目、毕业设计、简历模板、学习资料、面试题库、技术互助
收藏点赞不迷路 关注作者有好处
文末获取源码
语言环境:Python3.7
数据库:Mysql: mysql5.7
开发工具:IDEA 或其它
开发技术:Django框架,前端使用Layui+html
本项目基于Python语言开发实现,使用了Django WEB框架开发,前端使用Layui+HTML进行页面开发,提供了登录验证码和图形报表统计,以及数据导入导出的基本功能。
系统的用户角色可以灵活的自定义实现,目前设定的有管理员、班主任和普通用户等,可以根据需求自定义角色和权限,系统权限分为菜单级和按钮级,控制的十分细致,完全根据需要来控制对某些数据的增删改查操作,并根据需要给相应的用户授予相应的权限。
系统的主要功能模块包含:
用户管理:完成对用户信息的新增、查询和删除、导出等操作。
角色管理:完成对角色信息的新增、查询和编辑、删除、导出等操作。为角色授于不同的权限功能。
权限管理:完成对权限信息的新增、查询和删除、导出和启用等操作。
日志管理:主要对用户的操作日志进行查看和删除操作。
学校管理:完成对学校信息的新增、查询和删除操作。
年级管理:完成对年级信息的新增、查询和删除操作。
班级管理:完成对班级信息的新增、查询和删除操作。
课程管理:完成对课程信息的新增、查询和删除操作。
学生管理:完成对学生信息的新增、查询和删除操作,并可以进行批量导入和导出。
成绩录入:为每个学生进行成绩录入。
班级成绩:查询统计各学校各班级各学科的参考人数及各分数段的人数。
学生成绩:对所有学生的成绩信息进行管理和数据导入等操作。
数据统计:通过Echart图形报表完成相关数据统计。
个人资料修改:完成个人资料和密码的修改操作。
用户登录:
后台管理首页:
用户管理:
角色管理:
分配权限:
权限管理
日志管理
学校管理
年级管理
班级管理
课程管理
学生管理
成绩录入
班级成绩统计
学生成绩管理
# encoding:utf-8
import json
from io import BytesIO
from django.contrib.auth import logout
from django.contrib.auth.hashers import check_password, make_password
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
# Create your views here.
from common.API import res_josn_data
from common.API.auth import add_auth_session, login_required
from common.API.captcha import make_captcha
from common.API.code import check_code
from common.API.echarts import echarts_pie, json_response
from common.API.log import login_log
from login.models import Logo, Log
from sys_manage.models import User, Role, Power, RolePower
from student_score import models as m_model
def index(request):
if request.method == 'GET':
return redirect('/login')
def home(request):
if request.method == 'GET':
return render(request, 'login/home.html')
def login(request):
if request.method == 'GET':
return render(request, 'login/login.html')
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
code = request.POST.get('captcha')
if not username or not password or not code:
return res_josn_data.fail_api(msg="用户名或密码没有输入")
s_code = request.session.get("code", None)
print('验证码:', code, s_code)
user_ip = request.META.get('REMOTE_ADDR')
print(user_ip)
request.session["code"] = None
if not all([code, s_code]):
# login_log(request, uid=username, is_access=False, desc='验证码错误,请刷新验证码')
return res_josn_data.fail_api(msg="验证码错误,请刷新验证码!")
if code != s_code:
login_log(request, uid=username, is_access=False, desc='验证码错误')
return res_josn_data.fail_api(msg="验证码错误")
user = User.objects.filter(id_number=username).first()
if user is None:
login_log(request, uid=username, is_access=False, desc='用户不存在')
return res_josn_data.fail_api(msg="用户不存在!")
if user.user_status == 0:
login_log(request, uid=user.id_number, is_access=False, desc='用户被禁用')
return res_josn_data.fail_api(msg="用户被禁用!")
if username == user.id_number and check_password(password, user.id_password):
# 设置session过期时间
request.session.set_expiry(60 * 60 * 2)
# 登录
request.session["user_id"] = user.id_number
request.session["user_name"] = user.user_name
request.session["role_id"] = user.role_id
request.session["role_des"] = user.role_des
request.session["id"] = user.id
# 学校名称
request.session["department"] = user.department
# 年级
request.session["position"] = user.position
# 科目
request.session["email"] = user.email
# 记录登录日志
login_log(request, uid=user.id_number, is_access=True, desc='登录成功')
# 存入权限
add_auth_session(request)
return res_josn_data.success_api(msg="登录成功")
else:
login_log(request, uid=user.id_number, is_access=False, desc='密码错误')
return res_josn_data.fail_api(msg="密码错误")
def image_code(request):
""" 生成图片验证码 """
# 调用pillow函数,生成图片
img, code_string = check_code()
# 写入到自己的session中(以便于后续获取验证码再进行校验)
request.session['image_code'] = code_string
# 给Session设置60s超时
request.session.set_expiry(60)
stream = BytesIO()
img.save(stream, 'png')
return HttpResponse(stream.getvalue())
def get_captcha(request):
return make_captcha(request)
def login_in(request):
user_id = request.session.get('user_id')
if user_id:
return render(request, "login/index.html", {'user_id': user_id})
def login_out(request):
user_id = request.session.get('user_id')
login_log(request, uid=user_id, is_access=True, desc='退出登录')
logout(request)
return redirect('/login')
@login_required
def web_menu(request):
home_info = Logo.objects.filter(type='0').first()
logo_info = Logo.objects.filter(type='1').first()
title_info = Logo.objects.filter(type='2').first()
menu_info = Power.objects.filter(type=0).order_by('sort') # 目录
# 查询权限ID
menu_id = RolePower.objects.values_list('power_id').filter(role_id=request.session.get('role_id'))
permission_id = [i[0] for i in menu_id]
print(f'当前用户权限ID:{permission_id}')
menu_data = {
"homeInfo": {
"title": f"{home_info.name}",
"href": f"{home_info.url}"
},
"logoInfo": {
"title": f"{logo_info.name}",
"image": f"{logo_info.icon}",
"href": f"{logo_info.url}"
},
"menuInfo": [
{
"title": f"{title_info.name}",
"icon": f"{title_info.icon}",
"href": f"{title_info.url}",
"target": "_self",
"child": []
}
]
}
for item in menu_info:
if item.id in permission_id:
menu_data["menuInfo"][0]["child"].append({
"title": f"{item.name}",
"icon": f"{item.icon}",
"href": f"{item.code}",
"target": "_self",
"child": []
})
# 查询子菜单
sub_menu_info = Power.objects.filter(parent_id=item.id).order_by('sort')
for sub_item in sub_menu_info:
if sub_item.id in permission_id:
menu_data["menuInfo"][0]["child"][-1]["child"].append({
"title": f"{sub_item.name}",
"icon": f"{sub_item.icon}",
"href": f"{sub_item.code}",
"target": "_self"
})
return JsonResponse(menu_data, safe=False)
@login_required
def echarts(request):
if request.method == 'POST':
n_type = ['用户', '角色', '权限', '日志']
user_count = User.objects.count()
role_count = Role.objects.count()
role_power_count = RolePower.objects.count()
log_count = Log.objects.count()
data_list = [user_count, role_count, role_power_count, log_count]
title = '1.数量统计'
c = echarts_pie(n_type, data_list, title)
return json_response(json.loads(c))
@login_required
def user_setting(request):
if request.method == 'GET':
return render(request, "login/user_setting.html")
if request.method == "POST":
post_data = request.POST
print(post_data)
field_user_id = post_data['userID']
field_name = post_data['userName']
field_dep = post_data['department']
field_pos = post_data['position']
field_email = post_data['email']
update_dict = {
'user_name': field_name,
'department': field_dep,
'position': field_pos,
'email': field_email
}
User.objects.filter(id_number=field_user_id).update(**update_dict)
return res_josn_data.success_api(msg=f'用户:{field_user_id} 更新成功')
@login_required
def user_info_query(request):
data_list = []
post_data = request.POST
print('AJAX数据:', post_data)
login_id = post_data['login_id'].strip()
user_info = User.objects.filter(id_number=login_id).first()
role_info = Role.objects.filter(role_value=user_info.role_id).first()
return res_josn_data.user_setting_api(login_id, user_info.user_name, user_info.department, user_info.position,
role_info.name, user_info.email, data_list)
@login_required
def user_password(request):
if request.method == 'GET':
return render(request, "login/user_password.html")
if request.method == "POST":
post_data = request.POST
print(post_data)
login_id = post_data['login_id'].strip()
old_password = post_data['Param[old_password]']
new_password = post_data['Param[new_password]']
again_password = post_data['Param[again_password]']
user_obj = User.objects.filter(id_number=login_id).first()
if not user_obj:
return res_josn_data.fail_api(msg="用户不存在!")
if not check_password(old_password, user_obj.id_password):
return res_josn_data.fail_api(msg="旧密码错误!")
if new_password != again_password:
return res_josn_data.fail_api(msg="两次密码不一致!")
User.objects.filter(id_number=login_id).update(**{'id_password': make_password(new_password)})
return res_josn_data.success_api(msg="修改成功!")
# def page_not_found(request, exception):
# return render(request, "errors/404.html", exception)
#
#
# def page_error(request):
# return render(request, "errors/500.html")
# encoding:utf-8
import json
from django.contrib.auth.hashers import make_password
from django.core.paginator import Paginator
from django.shortcuts import render
from student_score import models as m_model
# Create your views here.
from common.API import res_josn_data
from common.API.auth import login_required, authorize
from sys_manage.models import User, Role
@login_required
def user_manage(request):
return render(request, 'sys_manage/user_manage/user_main.html')
@login_required
def user_query(request):
data_list = []
page = request.POST.get('page', 1)
limit = request.POST.get('limit', 10)
post_data_str = request.POST.get('Params', None)
if post_data_str is None:
user_obj = User.objects.all().order_by('id')
# return res_josn_data.table_api(data=data_list, count=0)
else:
post_data = json.loads(post_data_str)
id_number = post_data['idNumber']
user_name = post_data['userName']
user_dep = post_data['dep']
user_pos = post_data['position']
user_status = post_data['status']
user_role = post_data['role']
filters = {} # 查询参数构造
# model或数据库对应字段
orm_field = ['__gt', '__gte', '__lt', '__lte', '__exact', '__iexact', '__contains', '__icontains',
'__startswith', '__istartswith', '__endswith', '__iendswith', '__range', '__isnull', '__in']
filed_dict = {0: 'id_number', 1: 'user_name', 2: 'department', 3: 'position', 4: 'user_status', 5: 'role_id'}
param_list = [id_number, user_name, user_dep, user_pos, user_status, user_role]
for i in range(len(param_list)):
if param_list[i] not in (None, ''):
db_field = filed_dict[i] + orm_field[7]
filters[db_field] = param_list[i]
print('filters:', filters)
user_obj = User.objects.filter(**filters).order_by('id')
page_data = Paginator(user_obj, limit).page(page)
# 序号
count = (int(page) - 1) * int(limit)
for item in page_data:
count += 1
item_data = {
"id": count,
"fieldID": item.id,
"userID": item.id_number,
"name": item.user_name,
"department": item.department,
"position": item.position,
"email": item.email,
"status": item.user_status,
"role": item.role_des,
}
data_list.append(item_data)
return res_josn_data.table_api(count=len(user_obj), data=data_list)
@authorize(power='user:add', log=True)
def user_add(request):
if request.method == 'GET':
return render(request, 'sys_manage/user_manage/user_add.html')
if request.method == 'POST':
post_data = request.POST
print(request.POST)
user_id = post_data['userID']
user_password = post_data['password']
user_name = post_data['userName']
user_dep = post_data['department']
user_position = post_data['position']
user_email = post_data['email']
user_enable = post_data['enable']
role_value = post_data['role']
user_password_sha256 = make_password(user_password, salt=None, hasher='default')
role_obj = Role.objects.filter(role_value=role_value).first()
new_obj = User(
id_number=user_id,
id_password=user_password_sha256,
user_name=user_name,
department=user_dep,
position=user_position,
role_id=role_value,
role_des=role_obj.name,
user_status=user_enable,
email=user_email,
)
new_obj.save()
return res_josn_data.success_api(msg=f'用户:{user_name} 添加成功')
@login_required
def user_role_query(request):
if request.method == 'POST':
data_list = []
role_data = Role.objects.all()
for item in role_data:
item_data = {
"roleID": item.role_value,
"roleName": item.name
}
data_list.append(item_data)
print(data_list)
return res_josn_data.table_api(data=data_list, count=len(role_data))
def school_query(request):
if request.method == 'POST':
data_list = []
school_data = m_model.College.objects.all()
for item in school_data:
item_data = {
"schoolID": item.id,
"schoolName": item.name
}
data_list.append(item_data)
return res_josn_data.table_api(data=data_list, count=len(school_data))
@authorize(power='user:delete', log=True)
def user_delete(request):
if request.method == 'POST':
post_data = request.POST
print('AJAX数据:', post_data)
db_id = post_data['fieldID']
user_name = post_data['name']
User.objects.filter(id=db_id).delete()
return res_josn_data.success_api(f'用户:{user_name} 删除成功')
else:
return res_josn_data.fail_api(msg='请求权限不够!')
@authorize(power='user:delete', log=True)
def user_multi_delete(request):
if request.method == 'POST':
user_list = []
post_data_str = request.POST.get('Params', None)
post_data = json.loads(post_data_str)
for item in post_data:
db_id = item['fieldID']
user_name = item['name']
User.objects.filter(id=db_id).delete()
user_list.append(user_name)
return res_josn_data.success_api(f'用户:{user_list} 删除成功')
@login_required
def user_cell_edit(request):
# 前端字段和数据库字段对应dict
filed_dict = {
'userID': 'id_number',
'name': 'user_name',
'department': 'department',
'position': 'position',
'email': 'email',
}
if request.method == 'POST':
post_data = request.POST
print('AJAX数据:', post_data)
field_name = post_data['field']
field_value = post_data['value']
field_id = post_data['dbID']
User.objects.filter(id=field_id).update(**{filed_dict[field_name]: field_value})
return res_josn_data.success_api(f'更新成功')
@login_required
def user_role_edit(request):
if request.method == 'GET':
return render(request, 'sys_manage/user_manage/user_role_edit.html')
if request.method == 'POST':
post_data = request.POST
print(post_data)
user_id = post_data['userID']
role_id = post_data['role']
role_obj = Role.objects.filter(role_value=role_id).first()
update_dict = {
'role_id': role_id,
'role_des': role_obj.name
}
User.objects.filter(id_number=user_id).update(**update_dict)
return res_josn_data.success_api(msg=f'{user_id} 角色更新成功')
@authorize(power='user:enable', log=True)
def user_enable(request):
if request.method == 'POST':
post_data = request.POST
print('AJAX数据:', post_data)
field_id = post_data['userID']
enable_value = post_data['enableValue'] # 0禁用 1启用
enable_dict = {'enable': 1, 'disable': 0}
enable_dict_cn = {'enable': '启用', 'disable': '禁用'}
role_obj = User.objects.filter(id=field_id)
role_obj.update(**{'user_status': enable_dict[enable_value]})
return res_josn_data.success_api(msg=f'{role_obj[0].user_name} {enable_dict_cn[enable_value]}成功')
本次基于Python开发实现的学生成绩管理系统,也可作为学生管理系统使用,题目根据需要可以更改,功能实现较为完整,界面设计美观大方,适合作为毕业设计和课程设计使用。