Django实现在线考试系统的代码
时间: 2023-12-10 21:09:23 浏览: 94
P210627003J Python Django在线考试系统【程序】.rar
5星 · 资源好评率100%
好的,下面是一个简单的Django在线考试系统的代码示例,供您参考:
### models.py
```python
from django.db import models
from django.contrib.auth.models import User
class Question(models.Model):
title = models.CharField(max_length=256)
content = models.TextField()
options = models.TextField()
answer = models.CharField(max_length=256)
analysis = models.TextField()
difficulty = models.CharField(max_length=32)
class Paper(models.Model):
name = models.CharField(max_length=256)
description = models.TextField()
questions = models.TextField()
class Score(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
paper = models.ForeignKey(Paper, on_delete=models.CASCADE)
score = models.IntegerField()
start_time = models.DateTimeField(auto_now_add=True)
end_time = models.DateTimeField(auto_now=True)
```
### forms.py
```python
from django import forms
from .models import Score
class ExamForm(forms.ModelForm):
class Meta:
model = Score
fields = []
def __init__(self, *args, **kwargs):
self.paper = kwargs.pop('paper', None)
super().__init__(*args, **kwargs)
questions = self.paper.questions.split(',')
for question in questions:
self.fields[f'question_{question}'] = forms.CharField(widget=forms.RadioSelect(choices=[(i, x) for i, x in enumerate(self.get_options(question))]))
self.fields[f'question_{question}'].label = self.get_title(question)
def get_title(self, question_id):
question = Question.objects.get(id=question_id)
return question.title
def get_options(self, question_id):
question = Question.objects.get(id=question_id)
return question.options.split(',')
class PaperForm(forms.ModelForm):
class Meta:
model = Paper
fields = ['name', 'description', 'questions']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['questions'].widget.attrs.update({'class': 'form-control'})
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ['title', 'content', 'options', 'answer', 'analysis', 'difficulty']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['options'].widget.attrs.update({'class': 'form-control'})
self.fields['options'].widget.attrs.update({'rows': '3'})
self.fields['analysis'].widget.attrs.update({'class': 'form-control'})
self.fields['analysis'].widget.attrs.update({'rows': '3'})
```
### views.py
```python
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponseForbidden
from django.db.models import Avg, Count
from .models import Question, Paper, Score
from .forms import ExamForm, PaperForm, QuestionForm
def home(request):
papers = Paper.objects.all().annotate(num_questions=Count('questions'))
return render(request, 'exam/home.html', {'papers': papers})
@login_required
def exam(request, paper_id):
paper = Paper.objects.get(id=paper_id)
form = ExamForm(paper=paper)
if request.method == 'POST':
form = ExamForm(request.POST, paper=paper)
if form.is_valid():
score = 0
questions = paper.questions.split(',')
for question in questions:
answer = Question.objects.get(id=question).answer
if form.cleaned_data[f'question_{question}'] == answer:
score += 1
score = Score(user=request.user, paper=paper, score=score)
score.save()
return redirect('exam:score', score.id)
return render(request, 'exam/exam.html', {'paper': paper, 'form': form})
@login_required
def score(request, score_id):
score = Score.objects.get(id=score_id)
if score.user != request.user:
return HttpResponseForbidden()
return render(request, 'exam/score.html', {'score': score})
@login_required
def paper_create(request):
if request.method == 'POST':
form = PaperForm(request.POST)
if form.is_valid():
paper = form.save()
messages.success(request, '试卷创建成功!')
return redirect('exam:paper_edit', paper.id)
else:
form = PaperForm()
return render(request, 'exam/paper_form.html', {'form': form})
@login_required
def paper_edit(request, paper_id):
paper = Paper.objects.get(id=paper_id)
if request.method == 'POST':
form = PaperForm(request.POST, instance=paper)
if form.is_valid():
form.save()
messages.success(request, '试卷修改成功!')
return redirect('exam:paper_edit', paper.id)
else:
form = PaperForm(instance=paper)
return render(request, 'exam/paper_form.html', {'form': form, 'paper': paper})
@login_required
def question_create(request):
if not request.user.is_superuser:
return HttpResponseForbidden()
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, '题目创建成功!')
return redirect('exam:question_create')
else:
form = QuestionForm()
return render(request, 'exam/question_form.html', {'form': form})
```
### urls.py
```python
from django.urls import path
from . import views
app_name = 'exam'
urlpatterns = [
path('', views.home, name='home'),
path('exam/<int:paper_id>/', views.exam, name='exam'),
path('score/<int:score_id>/', views.score, name='score'),
path('paper/create/', views.paper_create, name='paper_create'),
path('paper/edit/<int:paper_id>/', views.paper_edit, name='paper_edit'),
path('question/create/', views.question_create, name='question_create'),
]
```
以上是在线考试系统的简单实现,您可以根据自己的需求进行修改和完善。如果您有任何问题或需要进一步的帮助,请随时联系我。
阅读全文