Start
This commit is contained in:
@@ -0,0 +1,530 @@
|
||||
from django.shortcuts import render, get_object_or_404, redirect
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django import forms
|
||||
|
||||
# from django.contrib.auth.models import User
|
||||
from django.contrib.auth.decorators import login_required, user_passes_test
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
from django.http import Http404, JsonResponse
|
||||
|
||||
from .forms import AnatomyAnswerForm, MarkAnatomyQuestionForm
|
||||
from .models import (
|
||||
AnatomyQuestion,
|
||||
CidUserAnswer,
|
||||
Exam,
|
||||
Answers,
|
||||
HalfMarkAnswers,
|
||||
IncorrectAnswers,
|
||||
)
|
||||
|
||||
from collections import defaultdict
|
||||
import os
|
||||
import base64
|
||||
import mimetypes
|
||||
import json
|
||||
import statistics
|
||||
import plotly.express as px
|
||||
|
||||
|
||||
def image_as_base64(image_file):
|
||||
"""
|
||||
:param `image_file` for the complete path of image.
|
||||
:param `format` is format for image, eg: `png` or `jpg`.
|
||||
"""
|
||||
# if not os.path.isfile(image_file):
|
||||
# return None
|
||||
|
||||
encoded_string = ""
|
||||
# with open(image_file, 'rb') as img_f:
|
||||
# encoded_string = base64.b64encode(img_f.read())
|
||||
encoded_string = base64.b64encode(image_file.file.read())
|
||||
mimetype, enc = mimetypes.guess_type(image_file.path)
|
||||
return "data:image/{};base64,{}".format(mimetype, encoded_string.decode("utf-8"))
|
||||
|
||||
|
||||
from django.template.defaulttags import register
|
||||
|
||||
|
||||
@register.filter
|
||||
def get_item(dictionary, key):
|
||||
return dictionary.get(key)
|
||||
|
||||
|
||||
def user_is_admin(user):
|
||||
if user:
|
||||
if user.pk == 1:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def question_list(request):
|
||||
questions = AnatomyQuestion.objects.all()
|
||||
return render(request, "anatomy/question_list.html", {"questions": questions})
|
||||
|
||||
|
||||
@login_required
|
||||
def index(request):
|
||||
exams = Exam.objects.all()
|
||||
return render(request, "anatomy/index.html", {"exams": exams})
|
||||
|
||||
|
||||
@login_required
|
||||
def question_detail(request, pk):
|
||||
question = get_object_or_404(AnatomyQuestion, pk=pk)
|
||||
return render(request, "anatomy/question_detail.html", {"question": question})
|
||||
|
||||
|
||||
@login_required
|
||||
def answer_question(request, pk):
|
||||
question = get_object_or_404(AnatomyQuestion, pk=pk)
|
||||
answer = question.user_answers.filter(
|
||||
user=request.user
|
||||
).first() # .filter(user=User)
|
||||
if request.method == "POST":
|
||||
if answer:
|
||||
form = AnatomyAnswerForm(request.POST, instance=answer)
|
||||
else:
|
||||
form = AnatomyAnswerForm(request.POST)
|
||||
if form.is_valid():
|
||||
answer = form.save(commit=False)
|
||||
answer.user = request.user
|
||||
answer.question = question
|
||||
# answer.published_date = timezone.now()
|
||||
answer.save()
|
||||
return redirect("question_detail", pk=pk)
|
||||
else:
|
||||
form = AnatomyAnswerForm(instance=answer)
|
||||
return render(
|
||||
request, "anatomy/answer_question.html", {"form": form, "question": question}
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def exam_list(request):
|
||||
exams = Exam.objects.all()
|
||||
return render(request, "anatomy/exam_list.html", {"exams": exams})
|
||||
|
||||
|
||||
@login_required
|
||||
def exam_overview(request, pk):
|
||||
print(type(pk))
|
||||
print(Exam.objects.all())
|
||||
exams = Exam.objects.all()
|
||||
print("test", Exam.objects.all().get(id=pk))
|
||||
exam = get_object_or_404(Exam, pk=pk)
|
||||
print("exam", exam)
|
||||
|
||||
questions = exam.exam_questions.all()
|
||||
|
||||
question_number = len(questions)
|
||||
|
||||
return render(
|
||||
request,
|
||||
"anatomy/exam_overview.html",
|
||||
{"exam": exam, "questions": questions, "question_number": question_number},
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def exam(request, pk, sk):
|
||||
exam = get_object_or_404(Exam, pk=pk)
|
||||
|
||||
questions = exam.exam_questions.all()
|
||||
|
||||
try:
|
||||
question = questions[sk]
|
||||
except IndexError:
|
||||
raise Http404("Exam question does not exist")
|
||||
|
||||
n = sk
|
||||
|
||||
question_details = {
|
||||
"total": len(questions),
|
||||
"current": n + 1,
|
||||
}
|
||||
|
||||
# Get data for flagged
|
||||
# answered_questions = UserAnswer.objects.filter(user=request.user).values_list("question__pk", flat=True)
|
||||
user_answer_data = UserAnswer.objects.filter(user=request.user).values_list(
|
||||
"question__pk", "answer", "flagged"
|
||||
)
|
||||
# flagged_questions = UserAnswer.objects.filter(user=request.user, flagged=True).values_list("question__pk", flat=True)
|
||||
# flagged_questions I= UserAnswer.filter(user=request.user, ).values_list("question__pk", flat=True)
|
||||
|
||||
answered_questions = set()
|
||||
flagged_questions = set()
|
||||
for ans_pk, answer, flagged in user_answer_data:
|
||||
if len(answer.strip()) > 0:
|
||||
answered_questions.add(ans_pk)
|
||||
if flagged:
|
||||
flagged_questions.add(ans_pk)
|
||||
|
||||
# u = question.user_answers
|
||||
answer = question.user_answers.filter(
|
||||
user=request.user
|
||||
).first() # .filter(user=User)
|
||||
if request.method == "POST":
|
||||
if answer:
|
||||
form = AnatomyAnswerForm(request.POST, instance=answer)
|
||||
else:
|
||||
form = AnatomyAnswerForm(request.POST)
|
||||
if form.is_valid():
|
||||
answer = form.save(commit=False)
|
||||
answer.user = request.user
|
||||
answer.question = question
|
||||
# answer.published_date = timezone.now()
|
||||
answer.save()
|
||||
if "next" in request.POST:
|
||||
return redirect("exam", pk=pk, sk=n + 1)
|
||||
elif "previous" in request.POST:
|
||||
return redirect("exam", pk=pk, sk=n - 1)
|
||||
else:
|
||||
form = AnatomyAnswerForm(instance=answer)
|
||||
return render(
|
||||
request,
|
||||
"anatomy/exam.html",
|
||||
{
|
||||
"exam": exam,
|
||||
"form": form,
|
||||
"question": question,
|
||||
"question_details": question_details,
|
||||
"questions": questions,
|
||||
"flagged_questions": flagged_questions,
|
||||
"answered_questions": answered_questions,
|
||||
"answer": answer,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def flag_question(request):
|
||||
pk = request.GET.get("pk", None)
|
||||
ans = UserAnswer.objects.filter(user=request.user, question__pk=pk).first()
|
||||
ans.flagged = not ans.flagged
|
||||
ans.save()
|
||||
data = {"flagged": ans.flagged}
|
||||
return JsonResponse(data)
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
def postExamAnswers(request):
|
||||
if request.is_ajax and request.method == "POST":
|
||||
|
||||
# horrible but it works
|
||||
for k in request.POST.dict():
|
||||
for q in json.loads(k):
|
||||
# As access is not restricted make sure the data appears valid
|
||||
if (not isinstance(q["cid"], int)) or (
|
||||
not isinstance(q["eid"], int) or (not isinstance(q["ans"], str))
|
||||
):
|
||||
return JsonResponse({"success": False})
|
||||
|
||||
# The model should catch invalid data but this should be less intensive
|
||||
max_int = 10000000
|
||||
if q["cid"] > max_int or q["eid"] > max_int:
|
||||
return JsonResponse({"success": False})
|
||||
|
||||
exiting_answers = CidUserAnswer.objects.filter(
|
||||
question__id=q["qid"], exam__id=q["eid"], cid=q["cid"]
|
||||
)
|
||||
|
||||
if not exiting_answers:
|
||||
ans = UserAnswer(answer=q["ans"], cid=q["cid"])
|
||||
ans.question_id = q["qid"]
|
||||
ans.exam_id = q["eid"]
|
||||
|
||||
ans.full_clean()
|
||||
|
||||
ans.save()
|
||||
else:
|
||||
# Update an existing answer
|
||||
# should never be more than one (famous last words)
|
||||
ans = exiting_answers[0]
|
||||
ans.answer = q["ans"]
|
||||
ans.save()
|
||||
|
||||
# print(UserAnswer.objects.filter(exam__id=q["eid"]))
|
||||
# print(request.urlencode())
|
||||
|
||||
return JsonResponse({"success": True})
|
||||
|
||||
# return render(request, "anatomy/exam.html", {"exam" : exam, "question" : question})
|
||||
|
||||
|
||||
@login_required
|
||||
@user_passes_test(user_is_admin, login_url="/accounts/login")
|
||||
def mark_overview(request, pk):
|
||||
exam = get_object_or_404(Exam, pk=pk)
|
||||
|
||||
questions = exam.exam_questions.all()
|
||||
|
||||
return render(
|
||||
request, "anatomy/mark_overview.html", {"exam": exam, "questions": questions}
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
@user_passes_test(user_is_admin, login_url="/accounts/login")
|
||||
def mark(request, pk, sk):
|
||||
exam = get_object_or_404(Exam, pk=pk)
|
||||
|
||||
questions = exam.exam_questions.all()
|
||||
|
||||
n = sk
|
||||
|
||||
question_details = {
|
||||
"total": len(questions),
|
||||
"current": n + 1,
|
||||
}
|
||||
|
||||
try:
|
||||
question = questions[sk]
|
||||
except IndexError:
|
||||
raise Http404("Exam question does not exist")
|
||||
|
||||
correct_answers = [i.answer for i in question.answers.all()]
|
||||
half_correct_answers = [i.answer for i in question.half_mark_answers.all()]
|
||||
incorrect_answers = [i.answer for i in question.incorrect_answers.all()]
|
||||
|
||||
user_answers = (
|
||||
set([i.answer for i in question.user_answers.all()])
|
||||
- set(correct_answers)
|
||||
- set(half_correct_answers)
|
||||
- set(incorrect_answers)
|
||||
) # .filter(user=User)
|
||||
user_answers = set([i for i in user_answers if i.strip() != ""])
|
||||
if request.method == "POST":
|
||||
|
||||
form = MarkAnatomyQuestionForm(request.POST)
|
||||
|
||||
if form.is_valid():
|
||||
cd = form.cleaned_data
|
||||
# correct = cd.get("correct")
|
||||
# half_correct = cd.get("half_correct")
|
||||
# incorrect = cd.get("incorrect")
|
||||
marked_answers = json.loads(cd.get("marked_answers"))
|
||||
|
||||
# This is mildly dangerous as we delete all answers
|
||||
question.answers.all().delete()
|
||||
question.half_mark_answers.all().delete()
|
||||
question.incorrect_answers.all().delete()
|
||||
|
||||
# This should probably use json (or something else...)
|
||||
# ajax.....
|
||||
for ans in marked_answers["correct"]:
|
||||
if ans.strip() == "":
|
||||
continue
|
||||
print("correct", ans)
|
||||
print(question.pk)
|
||||
a = Answers()
|
||||
a.question_id = question.pk
|
||||
a.answer = ans.strip()
|
||||
a.save()
|
||||
# for ans in half_correct.split("--//--"):
|
||||
for ans in marked_answers["half-correct"]:
|
||||
if ans.strip() == "":
|
||||
continue
|
||||
print("halfcorrect", ans)
|
||||
a = HalfMarkAnswers()
|
||||
a.question_id = question.pk
|
||||
a.answer = ans.strip()
|
||||
a.save()
|
||||
for ans in marked_answers["incorrect"]:
|
||||
if ans.strip() == "":
|
||||
continue
|
||||
print("incorrect", ans)
|
||||
a = IncorrectAnswers()
|
||||
a.question_id = question.pk
|
||||
a.answer = ans.strip()
|
||||
a.save()
|
||||
# answer = form.save(commit=False)
|
||||
# answer.user = request.user
|
||||
# answer.question = question
|
||||
# answer.published_date = timezone.now()
|
||||
# answer.save()
|
||||
if "next" in request.POST:
|
||||
return redirect("mark", pk=pk, sk=n + 1)
|
||||
elif "previous" in request.POST:
|
||||
return redirect("mark", pk=pk, sk=n - 1)
|
||||
else:
|
||||
form = MarkAnatomyQuestionForm()
|
||||
return render(
|
||||
request,
|
||||
"anatomy/mark.html",
|
||||
{
|
||||
"exam": exam,
|
||||
"form": form,
|
||||
"question": question,
|
||||
"question_details": question_details,
|
||||
"user_answers": user_answers,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def exam_json(request, pk):
|
||||
exam = get_object_or_404(Exam, pk=pk)
|
||||
|
||||
questions = exam.exam_questions.all()
|
||||
|
||||
exam_questions = defaultdict(dict)
|
||||
|
||||
for q in questions:
|
||||
exam_questions[q.id] = {
|
||||
"title": "{}".format(q.examination),
|
||||
"question": str(q.question_type),
|
||||
"images": [image_as_base64(q.image)],
|
||||
"type": "anatomy",
|
||||
}
|
||||
|
||||
exam_json = {
|
||||
"eid": exam.id,
|
||||
"exam_type": "anatomy",
|
||||
"exam_name": exam.name,
|
||||
"exam_mode": True,
|
||||
"questions": exam_questions,
|
||||
}
|
||||
return JsonResponse(exam_json)
|
||||
|
||||
|
||||
@login_required
|
||||
def exam_scores_cid(request, pk):
|
||||
exam = get_object_or_404(Exam, pk=pk)
|
||||
|
||||
questions = exam.exam_questions.all()
|
||||
|
||||
cids = (
|
||||
UserAnswer.objects.filter(question__in=questions)
|
||||
.values_list("cid", flat=True)
|
||||
.distinct()
|
||||
)
|
||||
|
||||
user_answers_and_marks = defaultdict(list)
|
||||
user_answers_marks = defaultdict(list)
|
||||
user_answers = defaultdict(list)
|
||||
user_names = {}
|
||||
|
||||
for cid in cids:
|
||||
# Convoluted (probably...)
|
||||
user_names[cid] = cid
|
||||
for q in questions:
|
||||
s = q.user_answers.filter(cid=cid)
|
||||
if not s:
|
||||
user_answers_marks[cid].append(0)
|
||||
user_answers[cid].append("")
|
||||
continue
|
||||
|
||||
ans = s[0].answer
|
||||
if ans in q.answers.all().values_list("answer", flat=True):
|
||||
a = 2
|
||||
elif ans in q.half_mark_answers.all().values_list("answer", flat=True):
|
||||
a = 1
|
||||
else:
|
||||
a = 0
|
||||
user_answers[cid].append(ans)
|
||||
user_answers_marks[cid].append(a)
|
||||
user_answers_and_marks[cid].append((ans, a))
|
||||
|
||||
user_scores = {}
|
||||
for user in user_answers_marks:
|
||||
user_scores[user] = sum(user_answers_marks[user])
|
||||
|
||||
user_scores_list = list(user_scores.values())
|
||||
mean = statistics.mean(user_scores_list)
|
||||
median = statistics.median(user_scores_list)
|
||||
try:
|
||||
mode = statistics.mode(user_scores_list)
|
||||
except statistics.StatisticsError:
|
||||
mode = "No unique mode"
|
||||
|
||||
df = user_scores_list
|
||||
fig = px.histogram(df, x=0)
|
||||
fig_html = fig.to_html()
|
||||
|
||||
total = len(questions)
|
||||
|
||||
return render(
|
||||
request,
|
||||
"anatomy/exam_scores.html",
|
||||
{
|
||||
"exam": exam,
|
||||
"questions": questions,
|
||||
"user_answers": dict(user_answers),
|
||||
"user_answers_marks": dict(user_answers_marks),
|
||||
"user_scores": user_scores,
|
||||
"user_names": user_names,
|
||||
"user_answers_and_marks": user_answers_and_marks,
|
||||
"mean": mean,
|
||||
"median": median,
|
||||
"mode": mode,
|
||||
"plot": fig_html,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def exam_scores(request, pk):
|
||||
exam = get_object_or_404(Exam, pk=pk)
|
||||
|
||||
questions = exam.exam_questions.all()
|
||||
|
||||
users = (
|
||||
UserAnswer.objects.filter(question__in=questions).values_list("user").distinct()
|
||||
)
|
||||
|
||||
user_answers_and_marks = defaultdict(list)
|
||||
user_answers_marks = defaultdict(list)
|
||||
user_answers = defaultdict(list)
|
||||
user_names = {}
|
||||
|
||||
for u in users:
|
||||
# Convoluted (probably...)
|
||||
user_names[u] = User.objects.filter(pk=u[0]).first().get_username()
|
||||
for q in questions:
|
||||
s = q.user_answers.filter(user__in=u)
|
||||
if not s:
|
||||
user_answers_marks[u].append(0)
|
||||
user_answers[u].append("")
|
||||
continue
|
||||
|
||||
ans = s[0].answer
|
||||
if ans in q.answers.all().values_list("answer", flat=True):
|
||||
a = 2
|
||||
elif ans in q.half_mark_answers.all().values_list("answer", flat=True):
|
||||
a = 1
|
||||
else:
|
||||
a = 0
|
||||
user_answers[u].append(ans)
|
||||
user_answers_marks[u].append(a)
|
||||
user_answers_and_marks[u].append((ans, a))
|
||||
|
||||
user_scores = {}
|
||||
for user in user_answers_marks:
|
||||
user_scores[user] = sum(user_answers_marks[user])
|
||||
|
||||
# Users with answers
|
||||
#
|
||||
# for q in questions:
|
||||
# answers = q.user_answers.all()
|
||||
#
|
||||
# for ans in answers:
|
||||
# user = ans.user
|
||||
# if ans.answer in q.answers.all().values_list("answer", flat=True):
|
||||
# user_answers[user].append(2)
|
||||
#
|
||||
|
||||
total = len(questions)
|
||||
|
||||
return render(
|
||||
request,
|
||||
"anatomy/exam_scores.html",
|
||||
{
|
||||
"exam": exam,
|
||||
"questions": questions,
|
||||
"user_answers": dict(user_answers),
|
||||
"user_answers_marks": dict(user_answers_marks),
|
||||
"user_scores": user_scores,
|
||||
"user_names": user_names,
|
||||
"user_answers_and_marks": user_answers_and_marks,
|
||||
},
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user