Files
PORTAL_COD2/src/back/tests/views.py
T
2025-01-29 14:54:06 +03:00

162 lines
6.5 KiB
Python

from rest_framework.views import APIView
from rest_framework.response import Response
from django.db.models import Count
from django.db.models import Q
from .models import *
from userauth.models import *
from .serializers import *
from datetime import datetime
from rest_framework import generics
from navigation.models import News
import json
from collections import defaultdict
import os
from django.conf import settings
from django.urls import reverse
import html
from rest_framework.permissions import IsAuthenticated
import base64
import hashlib
from cryptography.fernet import Fernet
from django.db.models import F
class TestListCreate(generics.ListCreateAPIView):
queryset = Test.objects.all()
serializer_class = TestSerializer
def post(self, request, *args, **kwargs):
# user = request.user
# user = User.objects.get(username="9966-00-125")
test = self.create(request, *args, **kwargs)
test_obj = Test.objects.get(id=test.data['id'])
# test = Test.objects.create(data=request.data, author=user)
questions_files = {file.name: file for file in request.FILES.getlist('questionsfiles')}
answers_files = {file.name: file for file in request.FILES.getlist('answersfiles')}
questions = json.loads(request.data['questions'])
for count, question_data in enumerate(questions, start=1):
question_image = questions_files.get(question_data['file']['name']) if 'file' in question_data and question_data['file'] is not None else None
question = TestQuestion.objects.create(
name=question_data['text'],
test=test_obj,
file=question_image,
numb=count,
settings=question_data.get('settings', {}),
)
for answer in question_data['answers']:
answer_image = answers_files.get(answer['file']['name']) if 'file' in answer and answer['file'] is not None else None
TestAnswer.objects.create(
name=answer['text'],
file=answer_image,
question=question
)
return test_obj
class TestDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Test.objects.all()
serializer_class = TestSerializer
lookup_url_kwarg = 'id'
lookup_field = 'id'
def get(self, request, *args, **kwargs):
test = self.get_object()
number_of_questions = test.question_count
random_questions = test.questions.order_by('?')[:number_of_questions]
test_serialized = TestSerializer(test).data
test_serialized['questions'] = TestQuestionSerializer(random_questions, many=True).data
return Response(test_serialized)
# class TestListCreate(generics.ListCreateAPIView):
# queryset = Test.objects.all()
# serializer_class = TestSerializer
# def get(self, request):
# user = request.user
# now = datetime.now()
# status = request.query_params.get('status')
# tests = self.get_tests_by_status(status, now)
# serialized_tests = TestSerializer(tests, many=True).data
# questions = TestQuestion.objects.filter(test__in=tests)
# questions_by_test_id = defaultdict(list)
# for question in questions:
# questions_by_test_id[question.test.id].append(question)
# for test in serialized_tests:
# test['is_passed'] = self.has_participated(user, test['id'])
# related_questions = questions_by_test_id[test['id']]
# test['files'] = [question.file.url for question in related_questions if question.file]
# return Response(serialized_tests)
# def get_tests_by_status(self, status, now):
# print(status)
# if status is None:
# return Test.objects.all().order_by('dateend')
# status_filters = {
# 'active': Test.objects.filter(dateend__gt=now),
# 'completed': Test.objects.filter(dateend__lt=now),
# }
# return status_filters.get(status, Test.objects.none()).order_by('dateend')
# def has_participated(self, employee, test):
# return TestResult.objects.filter(user=employee, answer__question__test=test).exists()
class GetTesting(APIView):
def get(self, request):
user = request.user
tests = Testing.objects.filter(user=user)
test_names = {test.id: test.test.name for test in tests}
serializer = TestingSeriaizer(tests, many=True).data
for test in serializer:
if test['id'] in test_names:
test['test_name'] = test_names[test['id']]
return Response(serializer)
class TestResultCreate(generics.ListCreateAPIView):
queryset = TestResult.objects.all()
serializer_class = TestResultSerializer
def post(self, request, *args, **kwargs):
answer_ids = [item['answer'] for item in request.data]
test_answers = TestAnswer.objects.filter(id__in=answer_ids)
serializer = self.get_serializer(data=request.data, many=True)
if serializer.is_valid():
Test.objects.filter(id=test_answer.question.test.id).update(attemps_number=F('attemps_number') - 1)
serializer.save()
self.create_testing(request, self.is_test_passed(test_answers))
return Response(self.is_test_passed(test_answers))
def create_testing(self, request, test_passed):
test_answer = TestAnswer.objects.select_related('question').get(id=request.data[0]['answer'])
user_id = request.data[0]['user']
user = User.objects.get(id=user_id)
Testing.objects.update_or_create(user=user, test=test_answer.question.test, completion_date= test_answer.question.test.dateend, defaults = {'test_passed': test_passed})
# Testing.objects.create(user=user, test=test_answer.question.test, completion_date=datetime.now(), test_passed=test_passed)
def is_test_passed(self, test_answers):
correct_questions = sum(
TestAnswer.objects.filter(
question=question, id__in=test_answers, right_wrong=True
).count() == TestAnswer.objects.filter(
question=question, right_wrong=True
).count() and TestAnswer.objects.filter(
question=question, id__in=test_answers, right_wrong=False
).count() == 0
for question in set(test_answers.values_list('question', flat=True))
)
pass_perc = test_answers[0].question.test.pass_perc
return correct_questions >= pass_perc