first commit

main
Lyanling 2 months ago
parent b3fb8680a6
commit 89801f2e62

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/mysite/polls/models.py" charset="UTF-8" />
</component>
</project>

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.7 (pythonProject02)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (pythonProject02)" project-jdk-type="Python SDK" />
</project>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/pythonProject02.iml" filepath="$PROJECT_DIR$/.idea/pythonProject02.iml" />
</modules>
</component>
</project>

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/homework3" vcs="Git" />
</component>
</project>

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite10_7.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

@ -0,0 +1,2 @@
import pymysql
pymysql.install_as_MySQLdb()

@ -0,0 +1,16 @@
"""
ASGI config for mysite10_7 project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite10_7.settings')
application = get_asgi_application()

@ -0,0 +1,130 @@
"""
Django settings for mysite10_7 project.
Generated by 'django-admin startproject' using Django 3.2.25.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os.path
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-50h(t$5-#_$h(#7)bdr-fr2)77c+v1$=n_0b82$z#*od_$_%ia'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite10_7.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite10_7.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'testdemo107',
'USER':'root',
'PASSWORD':'123456',
'HOST':'127.0.0.1',
'PORT':'3306'
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

@ -0,0 +1,23 @@
"""mysite10_7 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/', include('polls.urls')),
]

@ -0,0 +1,16 @@
"""
WSGI config for mysite10_7 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite10_7.settings')
application = get_wsgi_application()

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

@ -0,0 +1,6 @@
from django.apps import AppConfig
class PollsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'polls'

@ -0,0 +1,6 @@
from django import forms # 导入 Django 的表单模块
# 定义文件上传表单类
class UploadFileForm(forms.Form):
# 定义一个 FileField 用于处理文件上传label 是显示在表单中的标签
file = forms.FileField(label="Select an Excel file")

@ -0,0 +1,22 @@
# Generated by Django 3.2.25 on 2024-10-06 17:20
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='StudentInfo',
fields=[
('stu_id', models.CharField(max_length=20, primary_key=True, serialize=False)),
('stu_name', models.CharField(max_length=20)),
('stu_pwd', models.CharField(max_length=20)),
],
),
]

@ -0,0 +1,23 @@
# Generated by Django 3.2.25 on 2024-10-07 08:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('student_id', models.CharField(max_length=100, unique=True)),
('score', models.FloatField(default=0)),
('attendance_count', models.IntegerField(default=0)),
],
),
]

@ -0,0 +1,22 @@
from django.db import models
# Create your models here.
class StudentInfo(models.Model):
stu_id = models.CharField(primary_key=True, max_length=20)
stu_name = models.CharField(max_length=20)
stu_pwd = models.CharField(max_length=20)
# -----
from django.db import models
# 学生表
class Student(models.Model):
name = models.CharField(max_length=100)
student_id = models.CharField(max_length=100, unique=True) # 学号设为唯一
score = models.FloatField(default=0) # 积分允许为小数
attendance_count = models.IntegerField(default=0) # 到课次数
def __str__(self):
return self.name

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>确认点名</title>
</head>
<body>
<form method="post">
{% csrf_token %}
<h2>确认点名学生:</h2>
<p>姓名: {{ student.name }}</p>
<p>学号: {{ student.student_id }}</p>
<label for="attended">是否到达课堂:</label>
<input type="checkbox" name="attended" id="attended">
<label for="question_repeat">是否准确重复问题:</label>
<select name="question_repeat" id="question_repeat">
<option value="inaccurate">不准确</option>
<option value="accurate">准确</option>
</select>
<label for="answer_accuracy">回答问题准确性:</label>
<select name="answer_accuracy" id="answer_accuracy">
<option value="0">0分 - 未回答准确</option>
<option value="0.5">0.5分 - 回答部分正确</option>
<option value="1.5">1.5分 - 回答大部分正确</option>
<option value="3">3分 - 完全正确</option>
</select>
<button type="submit">确认并提交</button>
</form>
</body>
</html>

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="/polls/index/" method="post">
{% csrf_token %}
<p><label>用户名:</label><input name="user"/></p>
<p><label>密码:</label><input name="pwd"/></p>
<input type="submit" value="提交">
</form>
</body>
</html>

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<form action="/polls/register/" method="post">
{% csrf_token %}
<p><label>用户名:</label><input name="user"/></p>
<p><label>密码:</label><input name="pwd"/></p>
<input type="submit" value="注册">
</form>
</body>
</html>

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>随机点名</title>
</head>
<body>
<form method="post">
{% csrf_token %}
<button type="submit" name="start_roll_call">开始点名</button>
</form>
{% if selected_student %}
<h2>被选中的学生:</h2>
<p>姓名: {{ selected_student.name }}</p>
<p>学号: {{ selected_student.student_id }}</p>
{% endif %}
</body>
</html>

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">上传学生名单</button>
</form>
</body>
</html>

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,11 @@
from django.urls import path
from . import views
urlpatterns = [
path('',views.toLogin_view),
path('index/',views.Login_view),
path('toregister/',views.toregister_view),
path('register/',views.register_view),
path('upload/', views.upload_students, name='upload_students'),
path('roll_call/', views.roll_call, name='roll_call'),
path('confirm_roll_call/', views.confirm_roll_call, name='confirm_roll_call'), # 确认点名
]

@ -0,0 +1,103 @@
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
from django.shortcuts import render, redirect, get_object_or_404
import random
import pandas as pd
# 导入表单
from .forms import UploadFileForm
# Create your views here.
def toLogin_view(request):
return render(request,'login.html')
def Login_view(request):
u=request.POST.get("user",'')
p=request.POST.get("pwd",'')
if u and p:
c=StudentInfo.objects.filter(stu_name=u,stu_pwd=p).count()
if c >= 1:
return HttpResponse("登录成功!")
else:
return HttpResponse("账号密码错误!")
else:
return HttpResponse("请输入正确的账号和密码!")
def toregister_view(request):
return render(request, 'register.html')
# #点击注册后做的逻辑判断
def register_view(request):
u = request.POST.get("user", '')
p = request.POST.get("pwd", '')
if u and p:
stu = StudentInfo(stu_id=random.choice('0123456789'),stu_name=u, stu_pwd=p)
stu.save()
return HttpResponse("注册成功")
else:
return HttpResponse("请输入完整的账号和密码!")
#导入excel
# 上传学生名单的视图
def upload_students(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# 读取上传的 Excel 文件
excel_file = request.FILES['file']
df = pd.read_excel(excel_file) # 使用 pandas 读取 Excel 文件
# 遍历 DataFrame将每个学生保存到数据库
for _, row in df.iterrows():
student_id = row['student_id']
name = row['name']
Student.objects.get_or_create(student_id=student_id, name=name) # 如果学生已存在则不创建
return redirect('roll_call') # 完成后重定向到点名页面
else:
form = UploadFileForm()
return render(request, 'upload_students.html', {'form': form}) # 渲染上传页面
# 开始点名的视图
def roll_call(request):
students = Student.objects.all() # 获取所有学生
selected_student = None # 初始化被选中的学生
# 当教师点击“开始点名”按钮时
if request.method == 'POST' and 'start_roll_call' in request.POST:
# 设置权重:总分越高,被点名的概率越低
weights = [1 / (student.score + 1) for student in students] # 根据分数调整被点名概率
selected_student = random.choices(students, weights=weights, k=1)[0] # 随机选择一个学生
request.session['selected_student_id'] = selected_student.student_id # 存储被点名学生的ID到session中
return redirect('confirm_roll_call') # 跳转到确认点名页面
return render(request, 'roll_call.html', {'selected_student': selected_student}) # 渲染点名页面
# 确认点名的视图
def confirm_roll_call(request):
# 从 session 中获取被点名的学生
student_id = request.session.get('selected_student_id')
student = get_object_or_404(Student, student_id=student_id)
if request.method == 'POST':
# 学生是否到课
if 'attended' in request.POST: # 如果选择了到课
student.score += 1 # 到课加1分
student.attendance_count += 1 # 到课次数加1
# 处理是否准确重复问题
if request.POST['question_repeat'] == 'accurate':
student.score += 0.5 # 重复问题准确加0.5分
else:
student.score -= 1 # 重复问题不准确扣1分
# 处理回答问题的准确性0-3分
answer_accuracy = float(request.POST.get('answer_accuracy', 0))
student.score += answer_accuracy # 根据回答准确性加分
else:
student.score -= 5 # 未到课扣5分
student.save() # 保存更新后的学生信息
return redirect('roll_call') # 返回点名页面,进行下一轮点名
return render(request, 'confirm_roll_call.html', {'student': student}) # 渲染确认点名页面
Loading…
Cancel
Save