Compare commits

...

15 Commits

@ -1,3 +1,5 @@
from django.contrib import admin from django.contrib import admin
# Register your models here. # Register your models here.

@ -1,23 +1,48 @@
import jwt
from django.http import JsonResponse from django.http import JsonResponse
from EduSystemServer.settings import TOKEN_KEY
from EduSystemServer.utils import ResponseUtil
from Eduadmin.models import Admin
from Student.models import Student
from teacher.models import Teacher
class AuthMiddleware: class JWTMiddleware:
""" """
验证权限登录中间件 JWT中间件验证用户是否登录
""" """
def __init__(self, get_response): def __init__(self, get_response):
self.get_response = get_response self.get_response = get_response
def __call__(self, request): def __call__(self, request):
path = request.path # 检查请求的路径是否是登录路由,如果是,放行
if path in [ if request.path == '/login' \
"/login", or request.path == "/index" \
]: or request.path == "/" \
or request.path.startswith("/admin")\
or request.path.startswith("/static"):
response = self.get_response(request) response = self.get_response(request)
return response return response
# 从请求头中获取 Token
session = request.session token = request.META.get('HTTP_AUTHORIZATION', '')
if not session.get("username") and not session.get("type"): try:
return JsonResponse({"code": -1, "msg": "not login!"}, status=401) # 验证 Token
payload = jwt.decode(token, TOKEN_KEY, algorithms=['HS256'])
# 将解码后的 Token 数据存储在 request 中,以便视图可以访问
if payload.get("type") == "student":
if not Student.objects.filter(username=payload.get("username")).exists():
return JsonResponse(ResponseUtil.error("用户不存在!"), status=401)
if payload.get("type") == "teacher":
if not Teacher.objects.filter(username=payload.get("username")).exists():
return JsonResponse(ResponseUtil.error("用户不存在!"), status=401)
if payload.get("type") == "admin":
if not Admin.objects.filter(username=payload.get("username")).exists():
return JsonResponse(ResponseUtil.error("用户不存在!"), status=401)
request.jwt_payload = payload
except jwt.ExpiredSignatureError:
return JsonResponse(ResponseUtil.error("Token 失效,请重新登录!"), status=401)
except jwt.DecodeError:
return JsonResponse(ResponseUtil.error("Token Error"), status=401)
# 继续处理请求
response = self.get_response(request) response = self.get_response(request)
return response return response

@ -1,16 +0,0 @@
def jwt_response_payload_handler(token, user=None, request=None, role=None):
if user.username:
name = user.username
else:
name = user.username
return {
"authenticated": True,
'id': user.id,
"role": role,
'name': name,
'username': user.username,
'token': token,
}

@ -1,48 +1,70 @@
import json import json
from datetime import datetime, timedelta
from django.shortcuts import render import jwt
from django.http import JsonResponse, HttpResponse
# Create your views here.
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from Student.models import * from Student.models import *
from teacher.models import Teacher from teacher.models import Teacher
from EduSystemServer.utils import ResponseUtil from EduSystemServer.settings import TOKEN_KEY
from EduSystemServer.utils import *
# 用户登录成功后生成 JWT Token
def generate_jwt_token(user, _type):
# 设置 Token 的有效期
expiration_time = datetime.utcnow() + timedelta(hours=1)
print(datetime.utcnow())
print(expiration_time)
# 构建 Token 数据
payload = {
'type': _type,
'username': user.username,
'exp': expiration_time
}
# 使用密钥对数据进行签名生成 Token
token = jwt.encode(payload, TOKEN_KEY, algorithm='HS256')
return token
@csrf_exempt @csrf_exempt
def login(request): def login(request):
username = json.loads(request.body).get("username") """
password = json.loads(request.body).get("password") 登录
_type = json.loads(request.body).get("type") """
username = request.POST.get("username")
password = request.POST.get("password")
_type = request.POST.get("type")
if _type == "student": if _type == "student":
student = Student.objects.filter(username=username, student = Student.objects.filter(username=username,
password=password).first() password=password).first()
if student: if student:
request.session["username"] = student.username result = student.to_dict()
request.session["type"] = "student" result = ResponseUtil.ok(result, "login success!")
result = ResponseUtil.ok(student.to_dict(), "login success!") result["token"] = generate_jwt_token(student, "student").decode("utf-8")
result = {"code": 0, "message": "login success!"}
else: else:
result = {"code": -1, "message": "username or password error!"} result = {"code": -1, "message": "username or password error!"}
elif _type == "teacher": elif _type == "teacher":
teacher = Teacher.objects.filter(username=username, teacher = Teacher.objects.filter(username=username,
password=password).first() password=password).first()
if teacher: if teacher:
request.session["username"] = teacher.username result = teacher.to_dict()
request.session["type"] = "teacher" result = ResponseUtil.ok(result, "login success!")
result = ResponseUtil.ok(teacher.to_dict(), "login success!") result["token"] = generate_jwt_token(teacher, "teacher").decode("utf-8")
result = {"code": 0, "message": "login success!"}
else: else:
result = ResponseUtil.error("username or password error!") result = ResponseUtil.error("username or password error!")
else: else:
result = ResponseUtil.error("type error!") result = ResponseUtil.error("type error!")
return JsonResponse(result) response = JsonResponse(result)
return response
@csrf_exempt @csrf_exempt
def get_user_info(request): def get_user_info(request):
_type = request.GET.get("type") """
username = request.GET.get("username") 返回用户信息
"""
_type = request.jwt_payload.get("type")
username = request.jwt_payload.get("username")
if _type == "student": if _type == "student":
student = Student.objects.filter(username=username).first() student = Student.objects.filter(username=username).first()
result = ResponseUtil.ok(student.to_dict()) result = ResponseUtil.ok(student.to_dict())

@ -9,20 +9,11 @@ https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/ https://docs.djangoproject.com/en/2.2/ref/settings/
""" """
import datetime
import os import os
<<<<<<< Updated upstream
=======
CORS_ALLOW_ORIGIN_WHITELIST = [
"http://localhost:8080", # 允许访问的来源
"http://localhost:8000", # 允许访问的来源
# 可以继续添加其他允许的来源
]
CORS_ALLOW_CREDENTIALS = True # 允许跨域请求携带凭据例如Cookies
>>>>>>> Stashed changes
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@ -40,6 +31,8 @@ DEBUG = True
ALLOWED_HOSTS = ["*"] ALLOWED_HOSTS = ["*"]
# Application definition # Application definition
INSTALLED_APPS = [ INSTALLED_APPS = [
'django.contrib.admin', 'django.contrib.admin',
@ -65,40 +58,36 @@ MIDDLEWARE = [
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', 'corsheaders.middleware.CorsMiddleware',
<<<<<<< Updated upstream
'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware',
# 'API.middle.AuthMiddleware', 'API.middle.JWTMiddleware',
] ]
CORS_ALLOW_CREDENTIALS = True LOGGING = {
CORS_ORIGIN_ALLOW_ALL = True 'version': 1,
CORS_ALLOW_HEADERS = ( 'disable_existing_loggers': False,
'XMLHttpRequest', 'handlers': {
'X_FILENAME', 'console': {
'accept-encoding', 'level': 'DEBUG', # 调整日志级别为 DEBUG 以记录 SQL 查询
'authorization', 'class': 'logging.StreamHandler',
'content-type', },
'dnt', },
'origin', 'loggers': {
'user-agent', 'django.db.backends': {
'x-csrftoken', 'handlers': ['console'],
'x-requested-with', 'level': 'DEBUG',
'Pragma', 'propagate': False,
) },
},
}
=======
# 'API.middle.AuthMiddleware',
]
>>>>>>> Stashed changes
ROOT_URLCONF = 'EduSystemServer.urls' ROOT_URLCONF = 'EduSystemServer.urls'
TEMPLATES = [ TEMPLATES = [
{ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [], 'DIRS': [os.path.join(BASE_DIR, 'dist')],
'APP_DIRS': True, 'APP_DIRS': True,
'OPTIONS': { 'OPTIONS': {
'context_processors': [ 'context_processors': [
@ -165,3 +154,25 @@ USE_TZ = False
# https://docs.djangoproject.com/en/2.2/howto/static-files/ # https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/' STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'dist'),
)
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-requested-with',
'Cookie', # 添加Cookie到允许的头部
)
# token密钥
TOKEN_KEY = "eduSystem"

@ -14,28 +14,20 @@ Including another URLconf
2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
""" """
from django.contrib import admin from django.contrib import admin
from django.urls import path, include from django.urls import path, include, re_path
from API.views import login, get_user_info from django.views.generic import TemplateView
<<<<<<< Updated upstream
======= from API.views import login, get_user_info
>>>>>>> Stashed changes
urlpatterns = [ urlpatterns = [
path('Eduadmin/', admin.site.urls), path(r'', TemplateView.as_view(template_name='index.html')),
path('admin/', admin.site.urls),
path('api/', include(("API.urls", "api"), namespace="api")), path('api/', include(("API.urls", "api"), namespace="api")),
<<<<<<< Updated upstream
=======
<<<<<<< Updated upstream
>>>>>>> Stashed changes
path('teacher/', include(("teacher.urls", "teacher"), namespace="teacher")), path('teacher/', include(("teacher.urls", "teacher"), namespace="teacher")),
path('student/', include(("Student.urls", "student"), namespace="student")), path('student/', include(("Student.urls", "student"), namespace="student")),
path('course/', include(("course.urls", "course"), namespace="course")), path('course/', include(("course.urls", "course"), namespace="course")),
=======
path('student/', include(("Student.urls", "studnet"), namespace="student")),
>>>>>>> Stashed changes
path('login', login), path('login', login),
path('userinfo', get_user_info), path('userinfo', get_user_info),
] ]

@ -1,3 +1,21 @@
from functools import wraps
from django.http import JsonResponse
def permission(allowed_roles):
"""
装饰器权限控制
使用装饰器对路由视图进行权限控制
"""
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
if request.jwt_payload.get("type") in allowed_roles:
return view_func(request, *args, **kwargs)
else:
return JsonResponse(ResponseUtil.error("你没有权限访问该接口!"))
return _wrapped_view
return decorator
class ResponseUtil: class ResponseUtil:
@ -7,4 +25,4 @@ class ResponseUtil:
@staticmethod @staticmethod
def error(message="error!"): def error(message="error!"):
return {"code": -1, "message": message} return {"code": -1, "message": str(message)}

@ -1,3 +1,14 @@
from django.contrib import admin from django.contrib import admin
from django.core.paginator import Paginator
from Student.models import Student
# Register your models here. # Register your models here.
class StudentAdmin(admin.ModelAdmin):
list_display = ("username", "password", "name", "sex", "grade", "class_name", "major")
list_per_page = 5
list_filter = ('sex', 'grade', 'class_name', "major")
search_fields = ("name", "sex", "grade", "class_name", "major")
admin.site.register(Student, StudentAdmin)

@ -4,38 +4,6 @@ from django.db import models
# Create your models here. # Create your models here.
class Student(models.Model): class Student(models.Model):
sid = models.AutoField(primary_key=True, verbose_name="学生编号", name="sid") sid = models.AutoField(primary_key=True, verbose_name="学生编号", name="sid")
<<<<<<< Updated upstream
=======
<<<<<<< Updated upstream
>>>>>>> Stashed changes
<<<<<<< HEAD
s_username = models.CharField(max_length=30, verbose_name="用户名称", name="s_username", blank=True)
s_password = models.CharField(max_length=100, verbose_name="密码", name="s_password", blank=True)
s_name = models.CharField(max_length=100, verbose_name="姓名", name="s_name", blank=True)
s_sex = models.CharField(max_length=4, verbose_name="性别", name="s_sex", blank=True)
s_grade = models.CharField(max_length=20, verbose_name="年级", name="s_grade", blank=True)
s_class_name = models.CharField(max_length=50, verbose_name="班级", name="s_class_name", blank=True)
s_major = models.CharField(max_length=50, verbose_name="专业名称", name="s_major", blank=True)
def to_dict(self):
return {"sid": self.sid, "s_name": self.s_name, "s_username": self.s_username, "s_password": self.s_password,
"s_sex": self.s_sex, "s_grade": self.s_grade, "class_name": self.s_class_name, "s_major": self.s_major}
=======
username = models.CharField(max_length=30, verbose_name="用户名称", name="username", blank=True)
password = models.CharField(max_length=100, verbose_name="密码", name="password", blank=True)
name = models.CharField(max_length=100, verbose_name="姓名", name="name", blank=True)
sex = models.CharField(max_length=4, verbose_name="性别", name="sex", blank=True)
grade = models.CharField(max_length=20, verbose_name="年级", name="grade", blank=True)
class_name = models.CharField(max_length=50, verbose_name="班级", name="class_name", blank=True)
major = models.CharField(max_length=50, verbose_name="专业名称", name="major", blank=True)
def to_dict(self):
return {"sid": self.sid, "name": self.name, "username": self.username, "password": self.password,
"sex": self.sex, "grade": self.grade, "class_name": self.class_name, "major": self.major}
>>>>>>> 7b09141c358f80dd8877b8665d0d55b629db72aa
<<<<<<< Updated upstream
=======
=======
username = models.CharField(max_length=30, verbose_name="用户名称", name="username", blank=True) username = models.CharField(max_length=30, verbose_name="用户名称", name="username", blank=True)
password = models.CharField(max_length=100, verbose_name="密码", name="password", blank=True) password = models.CharField(max_length=100, verbose_name="密码", name="password", blank=True)
name = models.CharField(max_length=100, verbose_name="姓名", name="name", blank=True) name = models.CharField(max_length=100, verbose_name="姓名", name="name", blank=True)
@ -47,8 +15,6 @@ class Student(models.Model):
def to_dict(self): def to_dict(self):
return {"sid": self.sid, "name": self.name, "username": self.username, "password": self.password, return {"sid": self.sid, "name": self.name, "username": self.username, "password": self.password,
"sex": self.sex, "grade": self.grade, "class_name": self.class_name, "major": self.major} "sex": self.sex, "grade": self.grade, "class_name": self.class_name, "major": self.major}
>>>>>>> Stashed changes
>>>>>>> Stashed changes
class Meta: class Meta:
db_table = "student" db_table = "student"

@ -3,6 +3,9 @@ from django.urls import path
from .views import * from .views import *
urlpatterns = [ urlpatterns = [
path("", studnets), path("search", search_student),
path("selectCourse", get_select_course_by_id) path("selectCourse", select_course),
path("add", add_student),
path("delete", del_student),
path("getGrade", get_grade),
] ]

@ -1,123 +1,135 @@
import json
from django.core import serializers
from django.shortcuts import render from django.shortcuts import render
# Create your views here. # Create your views here.
from django.http import JsonResponse
<<<<<<< Updated upstream
from .models import Student
=======
<<<<<<< HEAD
from EduSystemServer.utils import ResponseUtil from course.models import SC, Course
from Student.models import Student
======= from EduSystemServer.utils import *
from .models import Student from .models import Student
>>>>>>> 1e084d20f30e0b66d5e309a483f87ce5cfe06c39
>>>>>>> Stashed changes
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from django.http import QueryDict from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from io import BytesIO
from django.http.multipartparser import MultiPartParser
@csrf_exempt
@permission(allowed_roles=["admin", "teacher"])
def add_student(request):
"""
添加学生
"""
if not request.method == "POST":
return JsonResponse(ResponseUtil.error("request method error!"))
try:
request_data = request.POST
student = Student()
student.username = request_data.get("username")
student.password = request_data.get("password")
student.name = request_data.get("name")
student.sex = request_data.get("sex")
student.grade = request_data.get("grade")
student.class_name = request_data.get("class_name")
student.major = request_data.get("major")
student.save()
result = ResponseUtil.ok(student.to_dict(), "添加成功!")
except Exception as E:
result = ResponseUtil.error(E)
return JsonResponse(result)
@csrf_exempt
@permission(allowed_roles=["admin", "teacher"])
def search_student(request):
"""
根据表单对学生进行模糊查询以及将查询的数据进行分页
"""
currentPage = request.GET.get("currentPage")
pageSize = request.GET.get("pageSize")
request_data = request.POST
search_students = Student.objects.all()
if not request_data.get("sid") == "":
search_students =search_students.filter(sid=request_data.get("sid"))
if not request_data.get("name") == "":
search_students =search_students.filter(name__contains=request_data.get("name"))
if not request_data.get("sex") == "":
search_students =search_students.filter(sex=request_data.get("sex"))
if not request_data.get("class_name") == "":
search_students =search_students.filter(class_name__contains=request_data.get("class_name"))
if not request_data.get("major") == "":
search_students =search_students.filter(major__contains=request_data.get("major"))
paginator = Paginator(search_students, pageSize)
try:
students = paginator.page(currentPage).object_list
except PageNotAnInteger:
students = paginator.page(1)
except EmptyPage:
students = paginator.page(paginator.num_pages).object_list
result = ResponseUtil.ok(json.loads(serializers.serialize("json", students)), "success!")
result["pageTotal"] = paginator.count
result["pageNum"] = paginator.num_pages
return JsonResponse(result)
@csrf_exempt
@permission(allowed_roles=["admin", "teacher"])
def del_student(request):
"""
根据学生ID删除学生
"""
if not request.method == "GET":
return JsonResponse(ResponseUtil.error("request method error!"))
try:
sid = request.GET.get("sid")
student = Student.objects.filter(sid=sid).first()
student.delete()
result = ResponseUtil.ok(None, "删除成功!")
except Exception as E:
result = ResponseUtil.error(E)
return JsonResponse(result)
@csrf_exempt @csrf_exempt
def studnets(request): @permission(allowed_roles=["admin", "student", "teacher"])
if request.method == "POST": def select_course(request):
try: """
request_data = json.loads(request.body) 选课
print(request_data) """
student = Student.objects.filter(sid=request_data.get("sid")).first() if not request.method == "POST":
student.username = request_data.get("username") return JsonResponse(ResponseUtil.error("request method error!"))
student.password = request_data.get("password") try:
student.name = request_data.get("name") request_data = request.POST
student.sex = request_data.get("sex") cid = request_data.get("cid")
student.grade = request_data.get("grade") username = request.jwt_payload.get("username")
student.class_name = request_data.get("class_name") student = Student.objects.filter(username=username).first()
student.major = request_data.get("major") if SC.objects.filter(cid=cid, sid=student.sid).exists():
student.save() return JsonResponse(ResponseUtil.error("该课程已经选择!"))
response = ResponseUtil.ok(student.to_dict(), "更新成功!") sc = SC()
return JsonResponse(response) sc.sid = student
except Exception as E: sc.cid = Course.objects.filter(cid=cid).first()
return JsonResponse(ResponseUtil.error(E)) sc.middle_grade = 0
elif request.method == "GET": sc.end_grade = 0
sid = request.GET.get('sid') sc.save()
s_name = request.GET.get('s_name') return JsonResponse(ResponseUtil.ok(None, "选课成功!"))
s_sex = request.GET.get('s_sex') except Exception as E:
s_grade = request.GET.get('s_grade') print(E)
s_class_name = request.GET.get('s_class_name') return JsonResponse(ResponseUtil.error(str(E)))
s_major = request.GET.get('s_major')
data = []
if sid:
filtered = Student.objects.filter(sid=sid)
for student in filtered:
data.append(student.to_dict())
elif s_name:
filtered = Student.objects.filter(s_name=s_name)
for student in filtered:
data.append(student.to_dict())
elif s_sex:
filtered = Student.objects.filter(s_sex=s_sex)
for student in filtered:
data.append(student.to_dict())
elif s_grade:
filtered = Student.objects.filter(s_grade=s_grade)
for student in filtered:
data.append(student.to_dict())
elif s_class_name:
filtered = Student.objects.filter(s_class_name=s_class_name)
for student in filtered:
data.append(student.to_dict())
elif s_major:
filtered = Student.objects.filter(s_major=s_major)
for student in filtered:
data.append(student.to_dict())
else:
all_objects = Student.objects.all()
for studnet in all_objects:
data.append(studnet.to_dict())
return JsonResponse({'code': 200, 'msg': 'success', 'data': data}, safe=False)
elif request.method == "DELETE":
parser = MultiPartParser(request.META, BytesIO(request.body), request.upload_handlers, request.encoding)
post_dict = parser.parse()
sid = post_dict[0]['sid']
try:
info = Student.objects.filter(sid=sid).get().to_dict()
Student.objects.filter(sid=sid).delete()
response = {"code": 200, "message": "删除成功!", "data": info}
return JsonResponse(response)
except:
response = {"code": 200, "message": "删除失败,未找到学生信息!"}
return JsonResponse(response)
elif request.method == "PUT":
put = MultiPartParser(request.META, request, request.upload_handlers, request.encoding).parse()
sid = put[0]['sid']
s_username = put[0]['s_username']
s_name = put[0]['s_name']
s_sex = put[0]['s_sex']
s_grade = put[0]['s_grade']
s_class_name = put[0]['s_class_name']
s_major = put[0]['s_major']
try:
Student.objects.filter(sid=sid).update(s_username=s_username, s_name=s_name, s_sex=s_sex, s_grade=s_grade,
s_class_name=s_class_name,
s_major=s_major)
except:
Student.objects.create(sid=sid, s_username=s_username, s_name=s_name, s_sex=s_sex, s_grade=s_grade,
s_class_name=s_class_name,
s_major=s_major)
data = Student.objects.filter(sid=sid)[0].to_dict()
return JsonResponse({'code': 200, 'msg': 'success', 'data': data}, safe=False)
student_list = Student.objects.all()
response_json = {"code": 200, "message": "success", "data": []}
for student in student_list:
response_json["data"].append(student.to_dict())
return JsonResponse(response_json)
elif request.method == 'DELETE':
params = QueryDict(request.body)
key = next(iter(params.keys())) # 获取键名
value = params.get(key) # 获取值
xx = str(value).split('-')[0]
print(xx.split('\r\n'))
return JsonResponse({'code': 200, 'msg': 'success'}, safe=False)
def get_select_course_by_id(request): @permission(allowed_roles=["student"])
pass def get_grade(request):
"""
获取学生成绩
"""
if not request.method == "GET":
return ResponseUtil.error("request method error!")
try:
username = request.jwt_payload.get("username")
student = Student.objects.filter(username=username).first()
grade__all = SC.objects.filter(sid=student.sid).values("sid", "sid__name", "cid__name", "cid__type", "cid__credit",
"cid__tid__name", "middle_grade", "end_grade").all()
grades = []
for grade in grade__all:
grades.append(grade)
return JsonResponse(ResponseUtil.ok(grades))
except Exception as E:
return JsonResponse(ResponseUtil.error(E))

@ -1,3 +1,45 @@
from django.contrib import admin from django.contrib import admin
from .models import Course, SC
# Register your models here. # Register your models here.
admin.site.site_header = '教务系统管理端'
class CourseAdmin(admin.ModelAdmin):
'''设置列表可显示的字段'''
list_display = ('cid', 'name', 'type', 'credit', "tid")
'''设置过滤选项'''
list_filter = ('name', 'credit', 'type')
'''每页显示条目数'''
list_per_page = 5
'''设置可编辑字段'''
list_editable = ('name', 'type', 'credit', "tid")
'''按发布日期排序'''
ordering = ('-credit',)
search_fields = ('name', 'type', 'credit', "tid")
class ScAdmin(admin.ModelAdmin):
list_display = ('student_name', 'course_name', 'middle_grade', 'end_grade')
list_per_page = 5
def student_name(self, obj):
print(obj)
return obj.sid.name
def course_name(self, obj):
return obj.cid.name
list_editable = ('middle_grade', "end_grade")
ordering = ('-end_grade',)
admin.site.register(Course, CourseAdmin)
admin.site.register(SC, ScAdmin)

@ -12,15 +12,15 @@ class Course(models.Model):
credit = models.IntegerField(verbose_name="课程学分", name="credit") credit = models.IntegerField(verbose_name="课程学分", name="credit")
tid = models.ForeignKey(Teacher, to_field="tid", on_delete=models.CASCADE, name="tid") tid = models.ForeignKey(Teacher, to_field="tid", on_delete=models.CASCADE, name="tid")
def to_dict(self):
return {"cid": self.cid, "c_name": self.name, "type": self.type, "credit": self.credit,
"tid": self.tid}
class Meta: class Meta:
db_table = "course" db_table = "course"
verbose_name = "课程" verbose_name = "课程"
verbose_name_plural = verbose_name verbose_name_plural = verbose_name
def to_dict(self):
return {"cid": self.cid, "c_name": self.name, "type": self.type, "credit": self.credit,
"tid": self.tid}
class SC(models.Model): class SC(models.Model):
sid = models.ForeignKey(Student, to_field="sid", on_delete=models.CASCADE, name="sid") sid = models.ForeignKey(Student, to_field="sid", on_delete=models.CASCADE, name="sid")
@ -33,6 +33,6 @@ class SC(models.Model):
class Meta: class Meta:
db_table = "sc" db_table = "sc"
verbose_name = "管理员" verbose_name = "选课"
verbose_name_plural = verbose_name verbose_name_plural = verbose_name
unique_together = ("sid", "cid") unique_together = ("sid", "cid")

@ -3,5 +3,9 @@ from django.urls import path
from course.views import * from course.views import *
urlpatterns = [ urlpatterns = [
path("", courses), path("getCourseById", get_course_by_student_id),
path("deleteSelectCourse", delete_select_course),
path("seacherCourse", search_course),
path("getStudentCourse", get_student_select_course),
path("editGrade", edit_grade)
] ]

@ -1,69 +1,145 @@
import json
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import F, Subquery, Max
from django.shortcuts import render from django.shortcuts import render
# Create your views here.
from django.http import JsonResponse from EduSystemServer.utils import *
from course.models import * from course.models import *
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from io import BytesIO
from django.http.multipartparser import MultiPartParser
def search_course(request):
"""
通过条件查询课程并且分页显示
"""
if not request.method == "GET":
return JsonResponse(ResponseUtil.error("request method error!"))
teacher_name = request.GET.get("tName")
course_name = request.GET.get("cName")
course_type = request.GET.get("cType")
current_page = request.GET.get("currentPage")
filter_course = Course.objects
if not teacher_name == "" and teacher_name is not None:
filter_course = Course.objects.filter(tid__name__contains=teacher_name)
if not course_name == "" and course_name is not None:
filter_course = Course.objects.filter(name__contains=course_name)
if not course_type == "" and course_type is not None:
filter_course = Course.objects.filter(type__contains=course_type)
filter_course = filter_course.values("name", "tid__name", "type", "credit",
"tid__title", "tid__education", "tid__dept", "cid").all()
paginator = Paginator(filter_course, 10)
try:
courses = paginator.page(current_page).object_list
except PageNotAnInteger:
courses = paginator.page(1).object_list
except EmptyPage:
courses = paginator.page(paginator.num_pages).object_list
courses_data = []
for course in courses:
courses_data.append(course)
result = ResponseUtil.ok(courses_data, "success!")
result["pageTotal"] = paginator.count
result["pageNum"] = paginator.num_pages
return JsonResponse(result)
@permission(allowed_roles=["student"])
def get_course_by_student_id(request):
"""
通过学生ID获取学生的选课
"""
if not request.method == "GET":
return JsonResponse(ResponseUtil.error("request method error!"))
s_username = request.jwt_payload.get("username")
student = Student.objects.filter(username=s_username).first()
sc_list = SC.objects.filter(sid=student.sid).values("sid__name", "cid__name", "cid__tid__name", "sid", "cid",
"cid__credit", "cid__tid__title", "cid__tid__dept", "cid__type").all()
data = []
for sc in sc_list:
data.append(sc)
result = ResponseUtil.ok(data)
return JsonResponse(result)
@permission(allowed_roles=["student"])
def delete_select_course(request):
"""
删除选课
"""
if not request.method == "GET":
return JsonResponse(ResponseUtil.error("request method error!"))
try:
sid = request.GET.get("sid")
cid = request.GET.get("cid")
sc = SC.objects.filter(cid=cid, sid=sid).first()
sc.delete()
return JsonResponse(ResponseUtil.ok(None, "退出选课成功!"))
except Exception as E:
return JsonResponse(ResponseUtil.error(E))
@csrf_exempt @csrf_exempt
def courses(request): @permission(allowed_roles=["teacher", "admin"])
if request.method == "POST": def get_student_select_course(request):
course = Course() """
course.c_name = request.POST.get("c_name") 获取所有学生的所有选课
course.type = request.POST.get('type') """
course.credit = request.POST.get("credit") if not request.method == "POST":
course.tid = request.POST.get('tid') return JsonResponse(ResponseUtil.error("request method error!"))
course.save() current_page = request.GET.get("currentPage")
response = {"code": 200, "message": "添加成功!", "data": course.to_dict()} sname = request.POST.get("sname")
return JsonResponse(response) className = request.POST.get("className")
elif request.method == "GET": courseName = request.POST.get("courseName")
cid = request.GET.get('cid') courseType = request.POST.get("courseType")
c_name = request.GET.get('c_name') sc_list = SC.objects.all().filter(
c_type = request.GET.get('type') sid__name__contains=sname,
tid = request.GET.get('tid') sid__class_name__contains=className,
data = [] cid__name__contains=courseName,
if cid: cid__type__contains=courseType
filtered = Course.objects.filter(cid=cid) ).annotate(
for item in filtered: sname=F("sid__name"),
data.append(item.to_dict()) className=F("sid__class_name"),
elif c_name: cname=F("cid__name"), ctype=F("cid__type"),
filtered = Course.objects.filter(c_name=c_name) endGrade=F("end_grade"),
for item in filtered: middleGrade=F("middle_grade")
data.append(item.to_dict()) ).values(
elif c_type: "sname", "className", "cname",
filtered = Course.objects.filter(type=c_type) "ctype", "endGrade", "middleGrade",
for item in filtered: "sid", "cid"
data.append(item.to_dict()) ).distinct()
elif tid: paginator = Paginator(sc_list, 10)
filtered = Course.objects.filter(tid=tid) try:
for item in filtered: sc_list = paginator.page(current_page).object_list
data.append(item.to_dict()) except PageNotAnInteger:
else: sc_list = paginator.page(1)
all_objects = Course.objects.all() except EmptyPage:
for item in all_objects: sc_list = paginator.page(paginator.num_pages).object_list
data.append(item.to_dict()) data = []
return JsonResponse({'code': 200, 'msg': 'success', 'data': data}, safe=False) for student in sc_list:
elif request.method == "DELETE": data.append(student)
delete = MultiPartParser(request.META, BytesIO(request.body), request.upload_handlers, request.encoding).parse() result = ResponseUtil.ok(data, "success!")
cid = delete[0]['cid'] result["pageTotal"] = paginator.count
try: result["pageNum"] = paginator.num_pages
info = Course.objects.filter(cid=cid).get().to_dict() return JsonResponse(result)
Course.objects.filter(cid=cid).delete()
response = {"code": 200, "message": "删除成功!", "data": info} @permission(allowed_roles=["teacher", "admin"])
return JsonResponse(response) @csrf_exempt
except: def edit_grade(request):
response = {"code": 200, "message": "删除失败,未找到课程信息!"} """
return JsonResponse(response) 成绩录入
elif request.method == "PUT": """
put = MultiPartParser(request.META, request, request.upload_handlers, request.encoding).parse() if not request.method == "POST":
cid = put[0]['cid'] return JsonResponse(ResponseUtil.error("request method error!"))
c_name = put[0]['c_name'] try:
c_type = put[0]['type'] sid = request.POST.get("sid")
credit = put[0]['credit'] cid = request.POST.get("cid")
tid = put[0]['tid'] sc = SC.objects.filter(sid=sid, cid=cid).first()
Course.objects.filter(cid=cid).update(c_name=c_name, type=c_type, credit=credit, tid=tid) sc.middle_grade = request.POST.get("middleGrade")
data = Course.objects.filter(cid=cid)[0].to_dict() sc.end_grade = request.POST.get("endGrade")
return JsonResponse({'code': 200, 'msg': 'success', 'data': data}, safe=False) sc.save()
return JsonResponse(ResponseUtil.ok(None, "成绩修改成功!"))
except Exception as E:
return JsonResponse(ResponseUtil.error(str(E)))

@ -0,0 +1 @@
.login-module{margin-top:60px;position:absolute;right:500px;text-align:center;width:30%}.el-header{background-color:#b3c0d1;color:#333;line-height:60px}.transfer-footer{margin-left:20px;padding:6px 5px}

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

@ -0,0 +1,19 @@
<!doctype html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="/static/favicon.ico">
<title>front</title>
<script defer="defer" src="/static/js/chunk-vendors.0bcf2d54.js"></script>
<script defer="defer" src="/static/js/app.8637dce5.js"></script>
<link href="/static/css/chunk-vendors.10dd4e95.css" rel="stylesheet">
<link href="/static/css/app.34ccc13b.css" rel="stylesheet">
</head>
<body>
<noscript><strong>We're sorry but front doesn't work properly without JavaScript enabled. Please enable it to
continue.</strong></noscript>
<div id="app"></div>
</body>
</html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

@ -1,3 +1,16 @@
from django.contrib import admin from django.contrib import admin
from teacher.models import Teacher
# Register your models here. # Register your models here.
class TeacherAdmin(admin.ModelAdmin):
list_display = ("username", "password", "name", "sex", "title", "education", "dept")
list_per_page = 5
list_filter = ("sex", "title", "education", "dept")
search_fields = ("name", "sex", "title", "education", "dept")
admin.site.register(Teacher, TeacherAdmin)

@ -10,7 +10,5 @@ from django.urls import path
from .views import * from .views import *
urlpatterns = [ urlpatterns = [
path("", teacher),
path('delete/',delete),
path('student/',student_performance_management)
] ]

@ -4,6 +4,8 @@ from django.shortcuts import render
# Create your views here. # Create your views here.
from django.http import JsonResponse from django.http import JsonResponse
from EduSystemServer.utils import ResponseUtil
from .models import Teacher from .models import Teacher
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from io import BytesIO from io import BytesIO
@ -12,114 +14,3 @@ from django.http import QueryDict
from course.models import Course,SC from course.models import Course,SC
from Student.models import Student from Student.models import Student
import json import json
@csrf_exempt
def teacher(request):
if request.method == "POST":
teacher_information = Teacher()
teacher_information.name = request.POST.get('name')
teacher_information.sex = request.POST.get('sex')
teacher_information.title = request.POST.get('title')
teacher_information.education = request.POST.get('education')
teacher_information.dept = request.POST.get('dept')
teacher_information.save()
print(teacher_information.name)
return JsonResponse({'code': 200, 'msg': 'success',"data": teacher_information.to_dict()}, safe=False)
elif request.method == "GET":
name = request.GET.get('name')
sex = request.GET.get('sex')
title = request.GET.get('title')
education = request.GET.get('education')
dept = request.GET.get('dept')
data = []
if name:
filtered = Teacher.objects.filter(name=name)
for teacher_x in filtered:
data.append(teacher_x.to_dict())
elif sex:
filtered = Teacher.objects.filter(sex=sex)
for teacher_x in filtered:
data.append(teacher_x.to_dict())
elif title:
filtered = Teacher.objects.filter(title=title)
for teacher_x in filtered:
data.append(teacher_x.to_dict())
elif education:
filtered = Teacher.objects.filter(education=education)
for teacher_x in filtered:
data.append(teacher_x.to_dict())
elif dept:
filtered = Teacher.objects.filter(dept=dept)
for teacher_x in filtered:
data.append(teacher_x.to_dict())
else:
all_objects = Teacher.objects.all()
for teacher_x in all_objects:
data.append(teacher_x.to_dict())
return JsonResponse({'code': 200, 'msg': 'success', 'data': data}, safe=False)
elif request.method == "DELETE":
parser = MultiPartParser(request.META, BytesIO(request.body), request.upload_handlers, request.encoding)
posdict = parser.parse()
print(posdict)
tid = int(posdict[0]['tid'])
print(tid)
try:
info = Teacher.objects.filter(tid=tid).get().to_dict()
Teacher.objects.filter(tid=tid).delete()
response = {"code": 200, "message": "删除成功!", "data": info}
return JsonResponse(response)
except:
response = {"code": 200, "message": "删除失败,未找到老师信息!"}
return JsonResponse(response)
elif request.method == 'PUT':
put = MultiPartParser(request.META, request, request.upload_handlers, request.encoding).parse()
# request.PUT = put[0]
print(put)
tid = put[0]['tid']
name = put[0]['name']
sex = put[0]['sex']
title = put[0]['title']
education = put[0]['education']
dept = put[0]['dept']
Teacher.objects.filter(tid=tid).update(name=name)
Teacher.objects.filter(tid=tid).update(sex=sex)
Teacher.objects.filter(tid=tid).update(title=title)
Teacher.objects.filter(tid=tid).update(education=education)
Teacher.objects.filter(tid=tid).update(dept=dept)
data = Teacher.objects.filter(tid=tid)[0].to_dict()
return JsonResponse({'code': 200, 'msg': 'success','data':data}, safe=False)
def delete(request):
tid = request.GET.get('tid')
try:
Teacher.objects.filter(tid = tid).delete()
return JsonResponse({'code': 200, 'msg': 'success'}, safe=False)
except:
return JsonResponse({'code': 200, 'msg': '删除失败'}, safe=False)
@csrf_exempt
def teaching_resources(request):
pass
@csrf_exempt
def student_performance_management(request):
if request.method == "POST":
sid = request.POST.get('sid')
cid = request.POST.get('cid')
middle_grade = float(request.POST.get('middle_grade'))
end_grade = float(request.POST.get('end_grade'))
if middle_grade <= 100 and middle_grade >= 0:
sc = SC()
sid = Student.objects.get(sid=sid)
print(sid)
cid = Course.objects.get(cid=cid)
sc.sid = sid
sc.cid = cid
sc.middle_grade = middle_grade
sc.end_grade=end_grade
sc.save()
return JsonResponse({'code': 200, 'msg': 'success'}, safe=False)
else:
return JsonResponse({'code': 200, 'msg': '成绩输入有误'}, safe=False)

@ -1,2 +1,63 @@
# EduSystem # EduSystem
### 使用手册
1. 创建数据库
```sql
create database edu_sys;
```
2. 修改`EduSystemServer/setting.py`文件中的配置
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "edu_sys",
'USER': "用户名",
'PASSWORD': "密码",
'HOST': "localhost",
'PORT': 3306,
}
}
```
3. 迁移模型至数据库
1. 生成迁移文件
```shell
python manage.py makemigrations Eduadmin
python manage.py makemigrations Student
python manage.py makemigrations teacher
python manage.py makemigrations course
```
2. 迁移
```python
python manage.py migrate
```
4. 创建admin用户
```python
python manage.py createsuperuser
# 输入用户名,邮箱,密码
```
5. 运行程序
```python
python manage.py runserver
```
### 访问网址
管理端http://127.0.0.1:8000/admin/
用户端http://127.0.0.1:8000

Loading…
Cancel
Save