示例#1
0
    def put(self, request):
        try:
            child_id = CbcEngine.get_engine().encrypt(request.data['child_id'])
            child = Child.objects.get(id_number=child_id)
            parent = child.parent
            if parent.user.username != request.user.username:
                raise exceptions.AuthenticationFailed(
                    detail='Not authorized request.')
        except KeyError:
            return Response('One of the fields are missing.',
                            status=status.HTTP_400_BAD_REQUEST)
        except Child.DoesNotExist:
            return Response('child does not exist.',
                            status=status.HTTP_400_BAD_REQUEST)

        request.data['child_id'] = child_id
        serializer = QuizSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
        try:
            serializer.save()
        except IntegrityError:
            return Response('Quiz is already exists',
                            status=status.HTTP_400_BAD_REQUEST)
        return Response('Quiz added successfully!')
示例#2
0
 def put(self, request):
     queryset = Quiz.objects.get(id=request.data['id'])
     serializer = QuizSerializer(queryset, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)
示例#3
0
 def put(self, request, pk, format=None):
     quiz = self.get_object(pk)
     serializer = QuizSerializer(quiz,
                                 data=request.data,
                                 context={'request': request})
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#4
0
 def post(self, request):
     serializer = QuizSerializer(data=request.data)
     try:
         if serializer.is_valid():
             serializer.save()
             return Response(serializer.data,
                             status=status.HTTP_201_CREATED)
     except Exception as e:
         return Response(serializer.errors,
                         status=status.HTTP_404_NOT_FOUND)
示例#5
0
    def test_get_draft_quizzes_for_user(self):
        """Test getting all drafted quizzes for creator."""
        response = self.client.get(reverse('quiz_drafts'))

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn(
            QuizSerializer(self.quiz_unpublished_user_1).data, response.data)
        self.assertNotIn(
            QuizSerializer(self.quiz_unpublished_user_2).data, response.data)
        self.assertNotIn(
            QuizSerializer(self.quiz_published_user_1).data, response.data)
示例#6
0
    def test_get_quizes_filtered_by_category(self):
        """Receive all quizzes filtered by given category."""
        response = self.client.get(reverse("quiz_list"),
                                   {'category': 'python'})

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn(
            QuizSerializer(self.quiz_published_1).data,
            response.data['results'])
        self.assertNotIn(
            QuizSerializer(self.quiz_published_2).data,
            response.data['results'])
示例#7
0
文件: views.py 项目: pu53/stelios
    def get(self, request, pk, format=None):
        user = User.objects.get(id=pk)
        profile = user.profile

        #all related subjects to a user
        subjects = profile.subjects.all()

        user_serializer = UserSerializer(user)
        user_data = user_serializer.data

        subject_list = []  #list of subjects for a given user
        quiz_list = []  #list of quizes for a given user

        #add all relevant subjects to a list
        for sub in subjects:
            subject_serializer = SubjectInfoSerializer(sub)
            subject_list.append(subject_serializer.data)

            #all quizes related to the subject
            quizes = Quiz.objects.filter(subject=sub.id)

            #add all relevant quizes to a list
            for quiz in quizes:
                quiz_serializer = QuizSerializer(quiz)
                quiz_list.append(quiz_serializer.data)

        content = {'subjects': subject_list}
        user_data.update(content)

        content = {'quizes': quiz_list}
        user_data.update(content)

        return Response(user_data)
示例#8
0
    def to_representation(self, instance):
        """
        Only quiz_ids are stored originally in concept sections
        Fetch quiz details from the quiz_ids
        """
        ret = super(ConceptSectionSerializer, self).to_representation(instance)
        if instance.has_quizzes():
            quiz_ids = ret['data']['quiz_ids']
            quiz_models = Quiz.get_detailed_quizzes_in(quiz_ids)
            quiz_list = QuizSerializer(quiz_models, many=True).data

            quiz_dict = {}
            for quiz in quiz_list:
                quiz_dict[quiz['id']] = quiz
            ordered_quizzes = []
            for quiz_id in quiz_ids:
                ordered_quizzes.append(quiz_dict[quiz_id])
            del ret['data']['quiz_ids']
            ret['data']['quizzes'] = ordered_quizzes

        elif instance.has_codequizzes():
            quiz_ids = ret['data']['quiz_ids']
            models = CodeQuiz.objects.filter(pk__in=quiz_ids)
            quizzes = CodeQuizSerializer(models, many=True).data
            
            quiz_dict = {}
            for quiz in quizzes:
                quiz_dict[quiz['id']] = quiz
            ordered_quizzes = []
            for quiz_id in quiz_ids:
                ordered_quizzes.append(quiz_dict[quiz_id])
            del ret['data']['quiz_ids']
            ret['data']['quizzes'] = ordered_quizzes
        return ret
示例#9
0
    def get_random_questions() -> []:
        questions = []

        if Quiz.objects.all().count() == 0:
            return None

        quiz = Quiz.objects.all().prefetch_related('answers').order_by('?')

        for question in quiz:
            data = {}
            question_data = QuizSerializer.QuizSerializer(question).data
            answers = question_data['answers']

            data['question_name'] = question_data['question']

            answers = Options.objects.filter(id__in=answers)
            data['answers'] = []
            for answer in answers:
                data['answers'].append({'answer': answer.option, 'answer_id': answer.id})

            data['question_key'] = question.id

            questions.append(data)

        return questions
示例#10
0
    def test_get_all_published_quizzes(self):
        """Get all quizzes that was already published"""
        response = self.client.get(reverse("quiz_list"))
        serialized_data = QuizSerializer(Quiz.objects.published(),
                                         many=True).data

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['results'], serialized_data)
        self.assertIn(
            QuizSerializer(self.quiz_published_1).data,
            response.data['results'])
        self.assertIn(
            QuizSerializer(self.quiz_published_2).data,
            response.data['results'])
        self.assertNotIn(
            QuizSerializer(self.quiz_not_published).data,
            response.data['results'])
示例#11
0
    def get(self, request, **kwargs):
        quiz_filter = self.request.query_params.get('quiz_id', None)
        qs = self.get_queryset()

        if quiz_filter:
            serializers = QuizSerializer(qs, many=True)
        else:
            serializers = QuestionSerializer(qs, many=True)
        return Response(serializers.data)
示例#12
0
    def test_get_quiz_detail(self):
        """Receive detail info about specific quiz."""
        serialized_data = QuizSerializer(self.quiz_published).data

        response = self.client.get(
            reverse('quiz_detail', args=(self.quiz_published.id, )))

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, serialized_data)
    def update(self, request, pk, format=None):
        """
        Pass in the pk of a topic as the 'pk'. We will use this topic and return a random quiz.

        curl -X PUT -H "Authorization: Bearer <Token>" -H "Content-Type: application/json"
         --data '{"no_of_questions":"<no_of_questions>","no_of_choices":"<no_of_choices>"}'
         "127.0.0.1:8000/api/generate_quiz/<topic_id>/"
         """
        try:
            # Get the relevant topic.
            topic = self.topic_queryset().get(id=pk)
        except Exception as e:
            # Topic does not exist.
            return Response({"error_description": "Topic does not exist"},
                            status=status.HTTP_400_BAD_REQUEST)

        if not topic.questions.all():
            return Response(
                {
                    "error_description":
                    "Topic has no questions. Add some questions to the topic first."
                },
                status=status.HTTP_400_BAD_REQUEST)

        serializer = QuizSerializer(data=request.data)

        if serializer.is_valid():
            no_of_questions = serializer.validated_data['no_of_questions']
            no_of_choices = serializer.validated_data['no_of_choices']
            show_all_alternative_answers = serializer.validated_data[
                'show_all_alternative_answers']
            fixed_choices_only = serializer.validated_data[
                'fixed_choices_only']

            randomly_generated_quiz = topic.generate_quiz(
                no_of_questions=no_of_questions,
                no_of_choices=no_of_choices,
                show_all_alternative_answers=show_all_alternative_answers,
                fixed_choices_only=fixed_choices_only).quiz
            return Response(randomly_generated_quiz,
                            status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#14
0
    def get(self, request, test_id):
        test = get_object_or_404(Quiz, pk=test_id)
        current_time = timezone.now()

        if current_time >= test.starting_time and current_time <= test.ending_time:
            serilizer = QuizSerializer(instance=test)
            return Response(serilizer.data)
        else:
            return Response(
                {'error': 'The Test Does\'t started or has been ended.'},
                status=status.HTTP_400_BAD_REQUEST)
示例#15
0
 def quizzes(self, request, pk=None):
     concept = get_object_or_404(Concept, pk=pk)
     self.check_object_permissions(request=request,
                                   obj=concept.group.course)
     serializer = QuizSerializer(concept.quizzes.all(), many=True)
     _playlist = typed_playlist.to_array(concept.playlist)
     ordered_data = []
     for elem in _playlist:
         if elem[2] == 1:
             ordered_data.append(serializer.data[elem[1]])
     return Response(ordered_data)
示例#16
0
class ConceptSerializer(serializers.ModelSerializer):
    """
    Serializer for Concept
    """
    videos = VideoSerializer(many=True)
    quizzes = QuizSerializer(many=True)
    pages = DocumentSerializer(many=True)

    class Meta:
        """
        Defining model
        """
        model = models.Concept
        fields = ('id', 'title', 'description', 'image', 'playlist', 'is_published')
示例#17
0
 def add_quiz(self, request, pk=None):
     concept = get_object_or_404(Concept, pk=pk)
     self.check_object_permissions(request, concept.group.course)
     serializer = AddQuizSerializer(data=request.DATA)
     if serializer.is_valid():
         quiz = Quiz(title=serializer.data['title'])
         quiz.save()
         concept.playlist = typed_playlist.append(quiz.id, concept.playlist,
                                                  1)
         concept.quizzes.add(quiz)
         concept.save()
         return Response(QuizSerializer(quiz).data)
     else:
         content = serializer.errors
         return Response(content, status.HTTP_400_BAD_REQUEST)
示例#18
0
    def course_pretest_quiz(self):
        section_type = ConceptSection.COURSE_PRETEST
        section = self.conceptsection_set.filter(type=section_type).last()
        if not section:
            return None

        quiz_ids = section.get_quiz_info()
        if not quiz_ids:
            return None

        quiz_id = quiz_ids[0]
        quiz = Quiz.get_detailed_quizzes_in([quiz_id]).first()
        if not quiz:
            # todo -> log error here
            return None
        serializer = QuizSerializer(quiz)
        return serializer.data
示例#19
0
 def post(self, request, *args, **kwargs):
     user = request.user
     data = request.data
     lesson = get_object_or_404(Lesson, pk=kwargs.get("pk"))
     quiz = {
         "owner": user.pk,
         "lesson": kwargs.get("pk"),
     }
     serializer = QuizSerializer(data=quiz)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return Response(serializer.data, status=HTTP_200_OK)
示例#20
0
    def get_quizzes_in_sections(klass, sections):
        quiz_sections = klass.get_quiz_sections(sections)

        all_quiz_ids = []
        section_id_by_quiz_id = {}
        section_quizzes = defaultdict(list)
        for section in quiz_sections:
            for quiz_id in section.get_quiz_info():
                all_quiz_ids.append(quiz_id)
                section_id_by_quiz_id[quiz_id] = section.id

        quizzes = Quiz.get_detailed_quizzes_in(all_quiz_ids)
        for quiz in quizzes:
            section_id = section_id_by_quiz_id[str(quiz.id)]
            serializer = QuizSerializer(quiz)
            section_quizzes[str(section_id)].append(serializer.data)

        return section_quizzes
示例#21
0
    def get(self, request, metric, scope, pk, format=json):
        """
		The view starts by checking the scope, and retrives data accordingly
		The options are quiz, question and user
		"""
        answer_data = {}
        scope_data = {}
        max_number_of_questions = 0
        if (scope == 'quiz'):
            answers = Answer.objects.filter(quizID=pk)
            answer_serializer = AnswerSerializerNoHistory(answers, many=True)
            answer_data = answer_serializer.data

            answers = []

            quiz = Quiz.objects.get(id=pk)
            quiz_serializer = QuizSerializer(quiz)
            scope_data = quiz_serializer.data

            answer_data = sorted(answer_data,
                                 key=lambda answer: self.findSortKey(answer))
            answer_data = sorted(answer_data,
                                 key=lambda answer: answer['questionID'])

            new_answer_data = []

            for answer in answer_data:
                new_answer_data.append({
                    'questionID': answer['questionID'],
                    'choiceID': answer['choiceID']
                })

            answer_data = new_answer_data

        data = {
            'title': scope_data["title"],
            'id': scope_data["id"],
            'answers': answer_data
        }
        return Response(data)
示例#22
0
 def post(self, request, pk, format=None):
     quiz = self.get_object(pk)
     quiz.publish()
     serializer = QuizSerializer(quiz)
     return Response(serializer.data, status=status.HTTP_200_OK)
示例#23
0
 def get(self, request, pk, format=None):
     quiz = self.get_object(pk)
     if quiz.is_published or quiz.creator == request.user:
         serializer = QuizSerializer(quiz)
         return Response(serializer.data, status=status.HTTP_200_OK)
     return Response({}, status=status.HTTP_404_NOT_FOUND)
示例#24
0
    def playlist_as_array(self, request, pk=None, with_history=False):
        """
        Gets all the elements in the playlist
        """
        concept = get_object_or_404(Concept, pk=pk)
        #videos_obj = concept.videos.all()
        videos_obj = []
        for elem in json.loads(concept.playlist):
            if elem[2] == 0:
                videos_obj.append(Video.objects.get(pk=elem[0]))
        pages_obj = concept.pages.all()
        #pages_obj = []
        #for elem in json.loads(concept.playlist):
        #    if elem[2] == 2:
        #        pages_obj.append(Document.objects.get(pk=elem[0]))

        quizzes_obj = concept.quizzes.all()

        videos = VideoSerializer(videos_obj, many=True)
        pages = [page.to_dict() for page in pages_obj]
        quizzes = QuizSerializer(quizzes_obj, many=True)
        _playlist = typed_playlist.to_array(concept.playlist)

        if with_history:
            videos_history = []
            for video in videos_obj:
                videohistory = VideoHistory.objects.filter(video=video,
                                                           user=request.user)
                if (len(videohistory) == 0):
                    videohistory = VideoHistory(video=video, user=request.user)
                    videohistory.save()
                else:
                    videohistory = videohistory[0]
                videos_history.append(
                    VideoHistorySerializer(videohistory).data)

            quizzes_history = []
            for quiz in quizzes_obj:
                quizhistory = ConceptQuizHistory.objects.filter(
                    quiz=quiz, user=request.user)
                if (len(quizhistory) == 0):
                    quizhistory = ConceptQuizHistory(quiz=quiz,
                                                     user=request.user)
                    quizhistory.save()
                else:
                    quizhistory = quizhistory[0]
                quizzes_history.append(
                    ConceptQuizHistorySerializer(quizhistory).data)

            pages_history = []
            for document in pages_obj:
                documenthistory = ConceptDocumentHistory.objects.filter(
                    document=document, user=request.user)
                if (len(documenthistory) == 0):
                    documenthistory = ConceptDocumentHistory(document=document,
                                                             user=request.user)
                    documenthistory.save()
                else:
                    documenthistory = documenthistory[0]
                pages_history.append(
                    ConceptDocumentHistorySerializer(documenthistory).data)

        ordered_data = []
        for elem in _playlist:
            if elem[2] == 0:
                next_item = {'type': 'video', 'content': videos.data[elem[1]]}
                if with_history:
                    next_item['history'] = videos_history[elem[1]]
            elif elem[2] == 1:
                next_item = {'type': 'quiz', 'content': quizzes.data[elem[1]]}
                if with_history:
                    next_item['history'] = quizzes_history[elem[1]]
            elif elem[2] == 2:
                next_item = {'type': 'document', 'content': pages[elem[1]]}
                if with_history:
                    next_item['history'] = pages_history[elem[1]]
            ordered_data.append(next_item)
        return ordered_data
示例#25
0
 def get(self, request):
     draft_quizzes = Quiz.objects.drafts(request.user.id)
     serializer = QuizSerializer(draft_quizzes, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
示例#26
0
 def get(self, request, format=None):
     queryset = self.get_quizes()
     serializer = QuizSerializer(queryset, many=True)
     return Response(data=serializer.data, status=status.HTTP_201_CREATED)