Compare commits

..

15 Commits

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" /> <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6" project-jdk-type="Python SDK" />
</project> </project>

@ -14,7 +14,21 @@
</component> </component>
<component name="NewModuleRootManager"> <component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" /> <content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.9" jdkType="Python SDK" /> <<<<<<< Updated upstream
=======
<<<<<<< Updated upstream
>>>>>>> Stashed changes
<<<<<<< HEAD
<orderEntry type="jdk" jdkName="Python 3.8 (2)" jdkType="Python SDK" />
=======
<orderEntry type="jdk" jdkName="Python 3.7 (EduSystemServer)" jdkType="Python SDK" />
>>>>>>> 7b09141c358f80dd8877b8665d0d55b629db72aa
<<<<<<< Updated upstream
=======
=======
<orderEntry type="jdk" jdkName="Python 3.7 (EduSystemServer)" jdkType="Python SDK" />
>>>>>>> Stashed changes
>>>>>>> Stashed changes
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
<component name="TemplatesService"> <component name="TemplatesService">

@ -1,11 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true"> <component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="@localhost" uuid="9660bbaf-5fdd-4aa5-8754-d2dc6487fc96"> <data-source source="LOCAL" name="edu_sys@localhost" uuid="fc67d607-329d-4381-af5b-a0e372257c56">
<driver-ref>mysql.8</driver-ref> <driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize> <synchronize>true</synchronize>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver> <jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://localhost:3306</jdbc-url> <jdbc-url>jdbc:mysql://localhost:3306/edu_sys</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
<data-source source="LOCAL" name="Django default" uuid="ffb088a0-406e-44b2-aed0-9587474966bf">
<driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize>
<imported>true</imported>
<remarks>$PROJECT_DIR$/EduSystemServer/settings.py</remarks>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://127.0.0.1:3306/edu_sys</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir> <working-dir>$ProjectFileDir$</working-dir>
</data-source> </data-source>
</component> </component>

@ -1,4 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" /> <<<<<<< Updated upstream
=======
<<<<<<< Updated upstream
>>>>>>> Stashed changes
<<<<<<< HEAD
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8 (2)" project-jdk-type="Python SDK" />
=======
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (EduSystemServer)" project-jdk-type="Python SDK" />
>>>>>>> 7b09141c358f80dd8877b8665d0d55b629db72aa
<<<<<<< Updated upstream
=======
=======
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (EduSystemServer)" project-jdk-type="Python SDK" />
>>>>>>> Stashed changes
>>>>>>> Stashed changes
</project> </project>

@ -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,17 +9,10 @@ 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
CORS_ALLOW_ORIGIN_WHITELIST = [
"http://localhost:8080", # 允许访问的来源
"http://localhost:8000", # 允许访问的来源
# 可以继续添加其他允许的来源
]
CORS_ALLOW_CREDENTIALS = True # 允许跨域请求携带凭据例如Cookies
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
@ -38,6 +31,8 @@ DEBUG = True
ALLOWED_HOSTS = ["*"] ALLOWED_HOSTS = ["*"]
# Application definition # Application definition
INSTALLED_APPS = [ INSTALLED_APPS = [
'django.contrib.admin', 'django.contrib.admin',
@ -63,33 +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',
'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,
) },
},
}
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': [
@ -156,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,16 +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 django.views.generic import TemplateView
from API.views import login, get_user_info from API.views import login, get_user_info
urlpatterns = [ urlpatterns = [
path('Eduadmin/', admin.site.urls), path(r'', TemplateView.as_view(template_name='index.html')),
path('api/', include(("API.urls", "API"), namespace="api")), path('admin/', admin.site.urls),
path('api/', include(("API.urls", "api"), namespace="api")),
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('admin/', include(("Eduadmin.urls", "Eduadmin"), namespace="Eduadmin")),
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)}

@ -7,9 +7,6 @@ class Admin(models.Model):
username = models.CharField(max_length=32, primary_key=True, name="username", verbose_name="管理员账号", blank=True) username = models.CharField(max_length=32, primary_key=True, name="username", verbose_name="管理员账号", blank=True)
password = models.CharField(max_length=128, name="password", verbose_name="管理员密码", blank=True) password = models.CharField(max_length=128, name="password", verbose_name="管理员密码", blank=True)
def to_dict(self):
return {"username": self.username, "password": self.password}
class Meta: class Meta:
db_table = "Eduadmin" db_table = "Eduadmin"
verbose_name = "管理员" verbose_name = "管理员"

@ -1,108 +1,3 @@
from django.shortcuts import render from django.shortcuts import render
from django.db.models import Q
# Create your views here.
from teacher.models import Teacher
from Student.models import Student
from course.models import SC, Course
from django.views.decorators.csrf import csrf_exempt
from django.http import QueryDict
from io import BytesIO
from django.http.multipartparser import MultiPartParser
import json
from django.http import JsonResponse
from EduSystemServer.utils import ResponseUtil
from .models import Admin
# 修改个人信息
@csrf_exempt
def admin_info(request):
if request.method == "POST":
try:
admin = Admin()
admin.username = request.POST.get("username")
admin.password = request.POST.get("password")
admin.save()
response = ResponseUtil.ok(admin.to_dict(), "添加成功!")
return JsonResponse(response)
except Exception as E:
return JsonResponse(ResponseUtil.error(E))
elif request.method == "GET":
username = request.GET.get("username")
try:
ad_info = Admin.objects.filter(username=username).values()
data = {
'管理员账号': ad_info[0]['username'],
'管理员密码': ad_info[0]['password']
}
response = ResponseUtil.ok(data, "查询成功!")
return JsonResponse(response)
except Exception as E:
return JsonResponse(ResponseUtil.error(E))
# 学生管理
@csrf_exempt
def student_manage(request):
if request.method == "GET":
student = Student.objects.all().values()
stu_list = []
for i in range(len(student)):
data = {
'学生编号': student[i]['sid'],
'用户账号': student[i]['username'],
'用户密码': student[i]['password'],
'姓名': student[i]['name'],
'性别': student[i]['sex'],
'年级': student[i]['grade'],
'班级': student[i]['class_name'],
'专业': student[i]['major'],
}
stu_list.append(data)
response = ResponseUtil.ok(stu_list, "学生信息查询成功!")
return JsonResponse(response)
elif request.method == "POST":
sid = request.GET.get('sid')
try:
stu_info = Student.objects.get(sid=sid)
username = request.POST.get("username") or stu_info.username
password = request.POST.get("password") or stu_info.password
name = request.POST.get("name") or stu_info.name
sex = request.POST.get("sex") or stu_info.sex
grade = request.POST.get("grade") or stu_info.grade
class_name = request.POST.get("class_name") or stu_info.class_name
major = request.POST.get("major") or stu_info.major
Student.objects.filter(sid=sid).update(username=username, password=password, name=name, sex=sex,
grade=grade, class_name=class_name, major=major)
except Exception as E:
return JsonResponse(ResponseUtil.error(E))
elif request.method == "DELETE":
delete = MultiPartParser(request.META, BytesIO(request.body), request.upload_handlers, request.encoding).parse()
sid = delete[0]['sid']
try:
info = Student.objects.filter(sid=sid).get().to_dict()
Student.objects.filter(sid=sid).delete()
response = ResponseUtil.ok(info, "删除成功!")
return JsonResponse(response)
except:
return JsonResponse(ResponseUtil.error("删除失败,未找到学生信息!"))
elif request.method == "PUT":
put = MultiPartParser(request.META, request, request.upload_handlers, request.encoding).parse()
sid = put[0]['sid']
username = put[0]['username']
name = put[0]['name']
sex = put[0]['sex']
grade = put[0]['grade']
class_name = put[0]['class_name']
major = put[0]['major']
if Student.objects.filter(sid=sid):
Student.objects.filter(sid=sid).update(username=username, name=name, sex=sex, grade=grade,
class_name=class_name,
major=major)
else:
return JsonResponse(ResponseUtil.error("没有查询到该同学!"))
data = Student.objects.filter(sid=sid)[0].to_dict()
return JsonResponse(ResponseUtil.ok(data, "修改成功!"))
# Create your views here.

@ -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)

@ -12,37 +12,37 @@ class Migration(migrations.Migration):
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='student', model_name='student',
name='class_name', name='s_class_name',
field=models.CharField(blank=True, max_length=50, verbose_name='班级'), field=models.CharField(blank=True, max_length=50, verbose_name='班级'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='student', model_name='student',
name='grade', name='s_grade',
field=models.CharField(blank=True, max_length=20, verbose_name='年级'), field=models.CharField(blank=True, max_length=20, verbose_name='年级'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='student', model_name='student',
name='major', name='s_major',
field=models.CharField(blank=True, max_length=50, verbose_name='专业名称'), field=models.CharField(blank=True, max_length=50, verbose_name='专业名称'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='student', model_name='student',
name='name', name='s_name',
field=models.CharField(blank=True, max_length=100, verbose_name='姓名'), field=models.CharField(blank=True, max_length=100, verbose_name='姓名'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='student', model_name='student',
name='password', name='s_password',
field=models.CharField(blank=True, max_length=100, verbose_name='密码'), field=models.CharField(blank=True, max_length=100, verbose_name='密码'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='student', model_name='student',
name='sex', name='s_sex',
field=models.CharField(blank=True, max_length=4, verbose_name='性别'), field=models.CharField(blank=True, max_length=4, verbose_name='性别'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='student', model_name='student',
name='username', name='s_username',
field=models.CharField(blank=True, max_length=30, verbose_name='用户名称'), field=models.CharField(blank=True, max_length=30, verbose_name='用户名称'),
), ),
migrations.AlterField( migrations.AlterField(

@ -15,6 +15,7 @@ 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}
class Meta: class Meta:
db_table = "student" db_table = "student"
verbose_name = "学生" verbose_name = "学生"

@ -3,10 +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("selectGrade/", search_grade), path("add", add_student),
path("changeInfo/", change_info), path("delete", del_student),
path("chooseCourse/", choose_course), path("getGrade", get_grade),
path("deleteCourse/",delete_course)
] ]

@ -1,25 +1,29 @@
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 HttpRequest
from django.http import JsonResponse
from EduSystemServer.utils import ResponseUtil
from .models import Student
from teacher.models import Teacher
from course.models import SC, Course from course.models import SC, Course
from EduSystemServer.utils import *
from .models import Student
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
import json
@csrf_exempt @csrf_exempt
def studnets(request): @permission(allowed_roles=["admin", "teacher"])
if request.method == "POST": def add_student(request):
"""
添加学生
"""
if not request.method == "POST":
return JsonResponse(ResponseUtil.error("request method error!"))
try: try:
request_data = json.loads(request.body) request_data = request.POST
print(request_data) student = Student()
student = Student.objects.filter(sid=request_data.get("sid")).first()
student.username = request_data.get("username") student.username = request_data.get("username")
student.password = request_data.get("password") student.password = request_data.get("password")
student.name = request_data.get("name") student.name = request_data.get("name")
@ -28,216 +32,104 @@ def studnets(request):
student.class_name = request_data.get("class_name") student.class_name = request_data.get("class_name")
student.major = request_data.get("major") student.major = request_data.get("major")
student.save() student.save()
response = ResponseUtil.ok(student.to_dict(), "添加成功!") result = ResponseUtil.ok(student.to_dict(), "添加成功!")
return JsonResponse(response)
except Exception as E: except Exception as E:
return JsonResponse(ResponseUtil.error(E)) result = ResponseUtil.error(E)
elif request.method == "GET": return JsonResponse(result)
sid = request.GET.get('sid')
name = request.GET.get('name')
sex = request.GET.get('sex')
grade = request.GET.get('grade')
class_name = request.GET.get('class_name')
major = request.GET.get('major')
data = []
if sid:
filtered = Student.objects.filter(sid=sid)
for student in filtered:
data.append(student.to_dict())
elif name:
filtered = Student.objects.filter(name=name)
for student in filtered:
data.append(student.to_dict())
elif sex:
filtered = Student.objects.filter(sex=sex)
for student in filtered:
data.append(student.to_dict())
elif grade:
filtered = Student.objects.filter(grade=grade)
for student in filtered:
data.append(student.to_dict())
elif class_name:
filtered = Student.objects.filter(class_name=class_name)
for student in filtered:
data.append(student.to_dict())
elif major:
filtered = Student.objects.filter(major=major)
for student in filtered:
data.append(student.to_dict())
else:
all_objects = Student.objects.all()
for student in all_objects:
data.append(student.to_dict())
response = ResponseUtil.ok(data, "查询成功!")
return JsonResponse(response)
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 = ResponseUtil.ok(info, "删除成功!")
return JsonResponse(response)
except:
return JsonResponse(ResponseUtil.error("删除失败,未找到学生信息!"))
elif request.method == "PUT":
put = MultiPartParser(request.META, request, request.upload_handlers, request.encoding).parse()
sid = put[0]['sid']
username = put[0]['username']
name = put[0]['name']
sex = put[0]['sex']
grade = put[0]['grade']
class_name = put[0]['class_name']
major = put[0]['major']
if Student.objects.filter(sid=sid):
Student.objects.filter(sid=sid).update(username=username, name=name, sex=sex, grade=grade,
class_name=class_name,
major=major)
else:
return JsonResponse(ResponseUtil.error("没有查询到该同学!"))
data = Student.objects.filter(sid=sid)[0].to_dict()
return JsonResponse(ResponseUtil.ok(data, "修改成功!"))
# 查询成绩
def search_grade(request): # 获取SID返回该同学的所有成绩
if request.method == "GET":
sid = request.GET.get('sid')
cid = SC.objects.filter(sid_id=sid).values()
data_list = []
for i in range(len(cid)):
c_name = Course.objects.filter(cid=cid[i]['cid_id']).values('name')[0]['name']
middle_grade = cid[i]['middle_grade']
end_grade = cid[i]['end_grade']
data = {
'c_name': c_name,
'平时成绩': middle_grade,
'最终成绩': end_grade
}
data_list.append(data)
return JsonResponse(ResponseUtil.ok(data_list, "成绩查询成功!"))
# 修改信息
@csrf_exempt @csrf_exempt
def change_info(request): @permission(allowed_roles=["admin", "teacher"])
if request.method == "GET": def search_student(request):
sid = request.GET.get('sid') """
info = Student.objects.filter(sid=sid).values() 根据表单对学生进行模糊查询以及将查询的数据进行分页
data = { """
'学生编号': sid, currentPage = request.GET.get("currentPage")
'用户账号': info[0]['username'], pageSize = request.GET.get("pageSize")
'用户密码': info[0]['password'], request_data = request.POST
'姓名': info[0]['name'], search_students = Student.objects.all()
'性别': info[0]['sex'], if not request_data.get("sid") == "":
'年级': info[0]['grade'], search_students =search_students.filter(sid=request_data.get("sid"))
'班级': info[0]['class_name'], if not request_data.get("name") == "":
'专业': info[0]['major'], search_students =search_students.filter(name__contains=request_data.get("name"))
} if not request_data.get("sex") == "":
return JsonResponse(ResponseUtil.ok(data, "个人信息查询成功!")) search_students =search_students.filter(sex=request_data.get("sex"))
elif request.method == "POST": if not request_data.get("class_name") == "":
sid = request.GET.get('sid') search_students =search_students.filter(class_name__contains=request_data.get("class_name"))
stu_info = Student.objects.get(sid=sid) if not request_data.get("major") == "":
username = request.POST.get('username') or stu_info.username search_students =search_students.filter(major__contains=request_data.get("major"))
password = request.POST.get('password') or stu_info.password paginator = Paginator(search_students, pageSize)
name = request.POST.get('name') or stu_info.name try:
sex = request.POST.get('sex') or stu_info.sex students = paginator.page(currentPage).object_list
grade = request.POST.get('grade') or stu_info.grade except PageNotAnInteger:
class_name = request.POST.get('class_name') or stu_info.class_name students = paginator.page(1)
major = request.POST.get('major') or stu_info.major except EmptyPage:
Student.objects.filter(sid=sid).update(username=username, password=password, name=name, sex=sex, grade=grade, students = paginator.page(paginator.num_pages).object_list
class_name=class_name, major=major) result = ResponseUtil.ok(json.loads(serializers.serialize("json", students)), "success!")
data = { result["pageTotal"] = paginator.count
'学生编号': sid, result["pageNum"] = paginator.num_pages
'用户账号': username, return JsonResponse(result)
'用户密码': password,
'姓名': name,
'性别': sex,
'年级': grade,
'班级': class_name,
'专业': major,
}
return JsonResponse(ResponseUtil.ok(data, "学生信息修改成功!"))
# 选课
@csrf_exempt @csrf_exempt
def choose_course(request): @permission(allowed_roles=["admin", "teacher"])
if request.method == "GET": # 将所有课程信息返回 def del_student(request):
course_list = [] """
course = Course.objects.all().values() 根据学生ID删除学生
for i in range(len(course)): """
teacher = Teacher.objects.filter(tid=course[i]['tid_id']).values('name') if not request.method == "GET":
data = { return JsonResponse(ResponseUtil.error("request method error!"))
'课程编号': course[i]['cid'],
'课程名称': course[i]['name'],
'课程类型': course[i]['type'],
'课程学分': course[i]['credit'],
'教师': teacher[0]['name'],
}
course_list.append(data)
return JsonResponse(ResponseUtil.ok(course_list, "课程查询成功!"))
elif request.method == "POST": # 将选择的课程添加到选课表
sid = request.GET.get('sid')
cid = request.POST.get('cid_id')
try: try:
SC.objects.create(sid_id=sid, cid_id=cid) sid = request.GET.get("sid")
course = Course.objects.filter(cid=cid).values() student = Student.objects.filter(sid=sid).first()
teacher = Teacher.objects.filter(tid=course[0]['tid_id']).values('name') student.delete()
data = { result = ResponseUtil.ok(None, "删除成功!")
'课程编号': cid, except Exception as E:
'课程名称': course[0]['name'], result = ResponseUtil.error(E)
'课程类型': course[0]['type'], return JsonResponse(result)
'课程学分': course[0]['credit'],
'教师': teacher[0]['name'],
}
return JsonResponse(ResponseUtil.ok(data, "选课成功!"))
except:
return JsonResponse(ResponseUtil.error("选课失败!"))
# 退课
@csrf_exempt @csrf_exempt
def delete_course(request): @permission(allowed_roles=["admin", "student", "teacher"])
if request.method == "GET": # 返回用户所有选择的课程 def select_course(request):
sid = request.GET.get('sid') """
course_list = [] 选课
try: """
cid = SC.objects.filter(sid_id=sid).values('cid_id') # 通过选课表找到学生选的所有课程 if not request.method == "POST":
for i in range(len(cid)): return JsonResponse(ResponseUtil.error("request method error!"))
course = Course.objects.filter(cid=cid[i]['cid_id']).values() # 在课程表中找课程详细信息
teacher = Teacher.objects.filter(tid=course[0]['tid_id']).values('name')
data = {
'课程编号': course[0]['cid'],
'课程名称': course[0]['name'],
'课程类型': course[0]['type'],
'课程学分': course[0]['credit'],
'教师': teacher[0]['name'],
}
course_list.append(data)
return JsonResponse(ResponseUtil.ok(course_list, "课程查询成功!"))
except:
return JsonResponse(ResponseUtil.error('你还没有选课!'))
elif request.method == "POST": # 将用户选择的课程删除
sid = request.GET.get('sid')
cid = request.POST.get('cid')
try: try:
course = Course.objects.filter(cid=cid).values() # 在课程表中找课程详细信息 request_data = request.POST
teacher = Teacher.objects.filter(tid=course[0]['tid_id']).values('name') cid = request_data.get("cid")
data = { username = request.jwt_payload.get("username")
'课程编号': course[0]['cid'], student = Student.objects.filter(username=username).first()
'课程名称': course[0]['name'], if SC.objects.filter(cid=cid, sid=student.sid).exists():
'课程类型': course[0]['type'], return JsonResponse(ResponseUtil.error("该课程已经选择!"))
'课程学分': course[0]['credit'], sc = SC()
'教师': teacher[0]['name'], sc.sid = student
} sc.cid = Course.objects.filter(cid=cid).first()
SC.objects.filter(sid_id=sid, cid_id=cid).delete() sc.middle_grade = 0
return JsonResponse(ResponseUtil.ok(data, "退课成功!")) sc.end_grade = 0
except: sc.save()
JsonResponse(ResponseUtil.error('退课失败!')) return JsonResponse(ResponseUtil.ok(None, "选课成功!"))
except Exception as E:
print(E)
return JsonResponse(ResponseUtil.error(str(E)))
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,12 +12,12 @@ class Migration(migrations.Migration):
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='course', model_name='course',
name='name', name='c_name',
field=models.CharField(blank=True, max_length=255, verbose_name='课程名称'), field=models.CharField(blank=True, max_length=255, verbose_name='课程名称'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='course', model_name='course',
name='type', name='c_type',
field=models.CharField(blank=True, max_length=128, verbose_name='课程类型'), field=models.CharField(blank=True, max_length=128, verbose_name='课程类型'),
), ),
] ]

@ -12,27 +12,27 @@ 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, "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")
cid = models.ForeignKey(Course, to_field="cid", on_delete=models.CASCADE, name="cid") cid = models.ForeignKey(Course, to_field="cid", on_delete=models.CASCADE, name="cid")
middle_grade = models.IntegerField(name="middle_grade", blank=True, null=True) middle_grade = models.IntegerField(name="middle_grade")
end_grade = models.IntegerField(name="end_grade", blank=True, null=True) end_grade = models.IntegerField(name="end_grade")
def to_dict(self): def to_dict(self):
return {"sid": self.sid, "cid": self.cid, "middle_grade": self.middle_grade, "end_grade": self.end_grade} return {"sid": self.sid, "cid": self.cid, "middle_grade": self.middle_grade, "end_grade": self.end_grade}
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,
cid__name__contains=courseName,
cid__type__contains=courseType
).annotate(
sname=F("sid__name"),
className=F("sid__class_name"),
cname=F("cid__name"), ctype=F("cid__type"),
endGrade=F("end_grade"),
middleGrade=F("middle_grade")
).values(
"sname", "className", "cname",
"ctype", "endGrade", "middleGrade",
"sid", "cid"
).distinct()
paginator = Paginator(sc_list, 10)
try:
sc_list = paginator.page(current_page).object_list
except PageNotAnInteger:
sc_list = paginator.page(1)
except EmptyPage:
sc_list = paginator.page(paginator.num_pages).object_list
data = [] data = []
if cid: for student in sc_list:
filtered = Course.objects.filter(cid=cid) data.append(student)
for item in filtered: result = ResponseUtil.ok(data, "success!")
data.append(item.to_dict()) result["pageTotal"] = paginator.count
elif c_name: result["pageNum"] = paginator.num_pages
filtered = Course.objects.filter(c_name=c_name) return JsonResponse(result)
for item in filtered:
data.append(item.to_dict()) @permission(allowed_roles=["teacher", "admin"])
elif c_type: @csrf_exempt
filtered = Course.objects.filter(type=c_type) def edit_grade(request):
for item in filtered: """
data.append(item.to_dict()) 成绩录入
elif tid: """
filtered = Course.objects.filter(tid=tid) if not request.method == "POST":
for item in filtered: return JsonResponse(ResponseUtil.error("request method error!"))
data.append(item.to_dict())
else:
all_objects = Course.objects.all()
for item in all_objects:
data.append(item.to_dict())
return JsonResponse({'code': 200, 'msg': 'success', 'data': data}, safe=False)
elif request.method == "DELETE":
delete = MultiPartParser(request.META, BytesIO(request.body), request.upload_handlers, request.encoding).parse()
cid = delete[0]['cid']
try: try:
info = Course.objects.filter(cid=cid).get().to_dict() sid = request.POST.get("sid")
Course.objects.filter(cid=cid).delete() cid = request.POST.get("cid")
response = {"code": 200, "message": "删除成功!", "data": info} sc = SC.objects.filter(sid=sid, cid=cid).first()
return JsonResponse(response) sc.middle_grade = request.POST.get("middleGrade")
except: sc.end_grade = request.POST.get("endGrade")
response = {"code": 200, "message": "删除失败,未找到课程信息!"} sc.save()
return JsonResponse(response) return JsonResponse(ResponseUtil.ok(None, "成绩修改成功!"))
elif request.method == "PUT": except Exception as E:
put = MultiPartParser(request.META, request, request.upload_handlers, request.encoding).parse() return JsonResponse(ResponseUtil.error(str(E)))
cid = put[0]['cid']
c_name = put[0]['c_name']
c_type = put[0]['type']
credit = put[0]['credit']
tid = put[0]['tid']
Course.objects.filter(cid=cid).update(c_name=c_name, type=c_type, credit=credit, tid=tid)
data = Course.objects.filter(cid=cid)[0].to_dict()
return JsonResponse({'code': 200, 'msg': 'success', 'data': data}, safe=False)

@ -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)

@ -12,27 +12,27 @@ class Migration(migrations.Migration):
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='teacher', model_name='teacher',
name='dept', name='t_dept',
field=models.CharField(blank=True, max_length=128, verbose_name='教师所属院系'), field=models.CharField(blank=True, max_length=128, verbose_name='教师所属院系'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='teacher', model_name='teacher',
name='education', name='t_education',
field=models.CharField(blank=True, max_length=128, verbose_name='教师学历'), field=models.CharField(blank=True, max_length=128, verbose_name='教师学历'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='teacher', model_name='teacher',
name='name', name='t_name',
field=models.CharField(blank=True, max_length=255, verbose_name='教师名称'), field=models.CharField(blank=True, max_length=255, verbose_name='教师名称'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='teacher', model_name='teacher',
name='sex', name='t_sex',
field=models.CharField(blank=True, max_length=128, verbose_name='教师性别'), field=models.CharField(blank=True, max_length=128, verbose_name='教师性别'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='teacher', model_name='teacher',
name='title', name='t_title',
field=models.CharField(blank=True, max_length=128, verbose_name='教师职称'), field=models.CharField(blank=True, max_length=128, verbose_name='教师职称'),
), ),
] ]

@ -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