Пример #1
0
    def test_saving_and_retrieving_questions(self):

        quiz_ = Quiz()
        quiz_.save()

        first_question = Question()
        first_question.question_text = 'The first (ever) quiz Question'
        first_question.quiz = quiz_
        first_question.save()

        second_question = Question()
        second_question.question_text = 'Question the second'
        second_question.quiz = quiz_
        second_question.save()

        saved_quiz = Quiz.objects.first()
        self.assertEqual(saved_quiz, quiz_)

        saved_questions = Question.objects.all()
        self.assertEqual(saved_questions.count(), 2)

        first_saved_question = saved_questions[0]
        second_saved_question = saved_questions[1]
        self.assertEqual(first_saved_question.question_text,
                         'The first (ever) quiz Question')
        self.assertEqual(first_saved_question.quiz, quiz_)
        self.assertEqual(second_saved_question.question_text,
                         'Question the second')
        self.assertEqual(second_saved_question.quiz, quiz_)
Пример #2
0
    def create(self, validated_data):
        q_uid = self.initial_data.get('q_uid')
        if q_uid is None:
            m_uid = Question.objects.all().aggregate(Max('uid')).get('uid__max')
            m_uid = 1 if m_uid is None else m_uid+1
        else:
            m_uid = int(q_uid)
        m_version = Question.objects.all().filter(uid=m_uid).aggregate(Max('version')).get('version__max')
        m_version = 1 if m_version is None else m_version+1
        answers = self.initial_data['answers']
        answers = self.validate_answers(answers)
        question = Question(uid=m_uid, version=m_version,
                            user=self.context['request'].user,
                            active=1, **validated_data)
        question.save()
        for one_answer in answers:
            q_answer = QuestionAnswer(question=question, **one_answer)
            try:
                q_answer.full_clean()
            except ValidationError as exc:
                question.delete()
                raise serializers.ValidationError(exc.message_dict)
            q_answer.save()

        return question
Пример #3
0
def bulk_quiz_create_view(request):
    if request.method == 'GET':
        return render(request, 'quiz/bulk.html')

    quiz_file = request.FILES['quiz-file']
    tree = xml_tree.parse(quiz_file)
    quiz_xml = tree.getroot()
    quiz_name = quiz_xml.attrib['title']
    quiz = Quiz(title=quiz_name,
                author=request.user,
                subject=request.user.teacherprofile.subject)
    quiz.save()
    for question_xml in quiz_xml:
        question = Question(prompt=question_xml.attrib['prompt'],
                            subject=request.user.teacherprofile.subject,
                            author=request.user,
                            quiz=quiz)
        question.save()
        for answer_xml in question_xml:
            answer = Answer(
                text=answer_xml.text,
                is_correct=True
                if answer_xml.attrib['correct'].lower() == 'yes' else False,
                question=question)
            answer.save()
    return redirect('teacher-detail', request.user.id)
Пример #4
0
 def handle(self, *args, **options):
     path = os.path.join(FIXTURES_PATH, "questions")
     print(path)
     files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
     for f in files:
         with open(os.path.join(path, f)) as j_file:
             js = json.loads(j_file.read())
             print("Current category: %s" % js['category'])
             t = Theme()
             t.name = js['category']
             t.save()
             for q in js['questions']:
                 question = Question()
                 question.theme = t
                 question.question = q['question']
                 #q['answer'] = q['answer'].replace(u'Другое','').strip()
                 ans = q['answer'].upper()
                 ans = ans.replace('"','')
                 ans = ans.replace("'",'')
                 ans = ans.replace(u"«",'')
                 ans = ans.replace(u"»",'')
                 try:
                     if len(ans.split(' '))==1 and len(ans.split('.'))==1:
                         question.answers = ans
                         try:
                             question.save()
                         except Exception as e:
                             print(str(e))
                 except:
                     pass
Пример #5
0
def update_quiz(request, id):
    data = json.loads(request.raw_post_data)
    quiz = Quiz.objects.get(id=id)
    quiz.title = data.get("title", quiz.title)
    quiz.subtitle = data.get("subtitle", quiz.subtitle)
    quiz.text = data.get("text", quiz.text)
    quiz.email = data.get("email", quiz.email)
    qids = []
    for qd in data.get("questions", []):
        qid = qd.get("id", None)
        if not qid:
            q = Question(index=qd['index'],
                         text=qd.get('text', ''),
                         choices=json.dumps(qd.get('choices', {})),
                         explanation=qd.get('explanation'),
                         correct=qd.get('correct', ''))
            q.save()
            qids.append(q.id)
            quiz.questions.add(q)
        else:
            q = Question.objects.get(id=qid)
            q.text = qd.get('text', '')
            q.choices = json.dumps(qd['choices'])
            q.correct = qd.get('correct', '')
            q.explanation = qd.get('explanation')
            q.index = qd['index']
            qids.append(q.id)
            q.save()
    # Look for questions that don't exist and delete them
    for q in Question.objects.filter(quiz=quiz):
        if not q.id in qids:
            q.delete()
    quiz.save()
    return retrieve_quiz(request, id)
Пример #6
0
def create_quiz(request):
    if request.method == "POST":
        question = request.POST.get('ques')
        option1 = request.POST.get('option1')
        option2 = request.POST.get('option2')
        option3 = request.POST.get('option3')
        option4 = request.POST.get('option4')
        cor_option = request.POST.get('cor_option')

        if cor_option == 'Select Option':
            messages.warning(
                request,
                "Warning! Please select a correct option for your question.")
            return redirect('/create_quiz/')

        obj = Question(ques=question,
                       option1=option1,
                       option2=option2,
                       option3=option3,
                       option4=option4,
                       cor_option=cor_option)
        obj.save()

        messages.success(request, "Success! Question Added Successfully.")

        questions = Question.objects.all()  # query set
        context = {'questions': questions}  # passing model into template
        return render(request, 'create_quiz.html', context)

    questions = Question.objects.all()
    context = {'questions': questions}
    return render(request, 'create_quiz.html', context)
Пример #7
0
def load_all(difficulty, stdout, stderr):
    category = Category.objects.get(title=u'Vše')
    category.enabled = True
    category.save()

    cache = {}

    attrs = [
        'difficulty', 'question', 'image', 'country', 'note', 'image_css_game',
        'image_css_recap', 'enabled'
    ]
    questions = list(
        Question.objects.filter(difficulty=difficulty).values(*attrs))
    for kwargs in questions:
        if kwargs['country'] not in cache:
            cache[kwargs['country']] = Country.objects.get(
                id=kwargs['country'])
        kwargs['country'] = cache[kwargs['country']]
        kwargs['category'] = category
        question = Question.objects.filter(**kwargs)
        if question.exists():
            stderr.write(
                u'Question for category "{}" already exist'.format(category))
            continue

        q = Question(**kwargs)
        q.save(ignore_tipi=True)
    def update(self, instance, validated_data):
        questions = validated_data.pop('questions')
        quiz = Quiz.objects.create(**validated_data, user=instance.user)
        quiz.save()
        for question in questions:
            answers = question.pop('answers')
            question = Question(**question)
            question.quiz = quiz
            question.save()
            for answer in answers:
                answer = Answer(**answer)
                answer.question = question
                answer.save()

        likes = Like.objects.filter(quiz=instance)
        for like in likes:
            like.quiz = quiz
            like.save()

        dislikes = Like.objects.filter(quiz=instance)
        for dislike in dislikes:
            dislike.quiz = quiz
            dislike.save()

        results = Result.objects.filter(quiz=instance)
        for result in results:
            result.quiz = quiz
            result.save()

        instance.delete()

        return quiz
Пример #9
0
def question():
    question = Question()
    question.question = "test_question"
    question.answer_A = "A"
    question.answer_B = "B"
    question.answer_C = "C"
    question.save()
    return point
Пример #10
0
 def setUp(self):
     u = Question(question='question',
                  day='1',
                  question_no='1',
                  answer='ans')
     # Question.objects.create(question='q2', day = '1', question_no = '2', answer = 'ans2')
     # Question.objects.create(question='question', day = '2', question_no = '1', answer = 'ans11')
     # Question.objects.create(question='q22', day = '2', question_no = '2', answer = 'ans22')
     u.save()
Пример #11
0
    def test_can_save_question_to_database(self):
        first_question = Question()
        first_question.text = '1 + 1 = 2'
        first_question.ans = 'True'
        first_question.save()

        saved_items = Question.objects.all()
        self.assertEqual(saved_items.count(), 1)

        second_question = Question()
        second_question.text = '1 = 2'
        second_question.ans = 'False'
        second_question.save()

        saved_items = Question.objects.all()
        self.assertEqual(saved_items.count(), 2)

        self.assertEqual(Question.objects.all()[0].text, '1 + 1 = 2')
        self.assertEqual(Question.objects.all()[1].text, '1 = 2')
Пример #12
0
def test(request):
    for i in range(25):
        theme = Theme(name='Test #{}'.format(i))
        theme.save()
        for j in range(30):
            question = Question(text='Question #{}'.format(j), theme=theme)
            question.save()
            for k in range(4):
                answer = Answer(question=question,
                                text='Answer #{}'.format(k),
                                is_correct=(k == j % 4))
                answer.save()
    return HttpResponse('ok')
Пример #13
0
def home_page(request):
    if request.method == 'POST':
        q = Question()
        question_text = request.POST.get('question_text', '')
        ans = request.POST.get('ans', '')
        q.text = question_text
        q.ans = ans
        q.save()

        return redirect('/')

    questions = Question.objects.all()
    return render(request, 'quiz/home.html', {'questions': questions})
Пример #14
0
    def create_questions_to_quiz(self, quiz: Quiz) -> None:
        how_many = random.randint(4, 8)
        question_objs = []
        questions = {f"{self.faker.sentence()}{i}?" for i in range(how_many)}
        for question in questions:
            question_objs.append(Question(
                quiz=quiz,
                question=question,
                explanation=self.faker.sentence()
            ))
        Question.objects.bulk_create(question_objs)

        for question in Question.objects.filter(question__in=questions):
            self.create_answers_to_question(question)
 def create(self, validated_data, user=None):
     questions = validated_data.pop('questions')
     quiz = Quiz.objects.create(**validated_data, user=user, is_moderated=user.licence_type == 'teacher')
     quiz.save()
     for question in questions:
         answers = question.pop('answers')
         question = Question(**question)
         question.quiz = quiz
         question.save()
         for answer in answers:
             answer = Answer(**answer)
             answer.question = question
             answer.save()
     return quiz
Пример #16
0
def get_quiz(request):
    """
    Return the non-archived quiz if the resourceLinkId and contextId pair exists, if not, then check whether the resourceLinkId exists. If it
    does, then a new quiz is to be created which would be copy of the latest non archived version of the quiz with given resourceLinkId 
    return new quiz.
    """
    live_quiz = Quiz.objects.filter(
        consumer_key=lti.get_oauth_consumer_key(request),
        resourceLinkId=lti.get_resource_link_id(request),
        contextId=lti.get_context_id(request))
    if live_quiz.exists():
        return live_quiz.latest()

    # The resourceLinkId and the contextId pair doesn't exists, check whether the resourceLinkId exists.
    if Quiz.objects.filter(
            consumer_key=lti.get_oauth_consumer_key(request),
            resourceLinkId=lti.get_resource_link_id(request)).exists():
        # The quiz link is being migrated to another Context (new course term), hence the non-archived
        # latest quiz with same resourceLinkId has to be copied over as a new Quiz.
        quiz = create_new_quiz(request)
        latest_quiz = Quiz.objects.filter(
            consumer_key=lti.get_oauth_consumer_key(request),
            resourceLinkId=lti.get_resource_link_id(request)).latest()
        # copy all the settings of the latest quiz associated with the RESOURCE LINK ID.
        quiz_settings = QuizSettings.objects.get(quiz=quiz)
        quiz_settings.duration = latest_quiz.duration
        quiz_settings.timeBetweenAttempt = latest_quiz.timeBetweenAttempt
        quiz_settings.maxAttempts = latest_quiz.maxAttempts
        quiz_settings.graded = latest_quiz.graded
        quiz_settings.save()
        #TODO: Copy all the questions , doing it manually to avoid any useless trouble: is it the right way?
        questions = get_questions_by_quiz(latest_quiz)
        for question in questions:
            new_question = Question()
            new_question.quiz = question.quiz  # change the quiz to the new quiz
            new_question.question_type = question.question_type
            new_question.serial_number = question.serial_number
            new_question.question_weight = question.question_weight
            new_question.statement = question.statement
            new_question.options_data = question.options_data
            new_question.expected_response = question.expected_response
            new_question.other_data = question.other_data
            new_question.published = question.published
            new_question.save()

        return quiz

    # The quiz doesn't exists for associated request! Return False
    return False
Пример #17
0
def quiz():
    category = Category()
    category.name = "teste_category"
    category.save()

    question = Question()
    question.question = "test_question"
    question.answer_A = "test_A"
    question.answer_B = "test_B"
    question.answer_C = "test_C"
    question.save()

    quiz = Quiz()
    quiz.title = "test_quiz"
    quiz.category = category
    quiz.save()
    quiz.question.add(question)
    return quiz
Пример #18
0
def add_question(request):
    if request.method == "POST":
        question = request.POST.get("question")
        option1 = request.POST.get("option1")
        option2 = request.POST.get("option2")
        option3 = request.POST.get("option3")
        option4 = request.POST.get("option4")
        answer = request.POST.get("answer")
        exam = request.POST.get("exam")
        q = Question()
        q.question = question
        q.option1 = option1
        q.option2 = option2
        q.option3 = option3
        q.option4 = option4
        q.answer = answer
        q.exam = Exam.objects.get(pk=int(exam))
        q.save()
        return HttpResponse("success")
Пример #19
0
def create_test():
    data = request.get_json()
    questions = []

    for q in data['questions']:
        answers = []
        for answer in q['answers']:
            answer = Answer(answer=answer['answer'],
                            is_correct=answer.get('is_correct'))
            answers.append(answer)

        q = Question(question=q['question'], answers=answers)
        questions.append(q)

    duration = data['duration']

    test = Test(name=data['name'], questions=questions, duration=duration)
    db.session.add(test)
    db.session.commit()
    return jsonify(test.to_dict()), 201
Пример #20
0
def create_quiz_questions(user, quiz, quiz_obj):
    for q in quiz_obj['questions']:

        question = Question(owner=user,
                            type=q['question']['type'],
                            title=clean_lang_dict(q['question']['title']))

        question.save()

        quiz_question = QuizQuestion(quiz=quiz,
                                     question=question,
                                     order=q['order'])
        quiz_question.save()

        q['id'] = quiz_question.pk
        q['question']['id'] = question.pk

        for prop in q['question']['props']:
            if prop != 'id':
                QuestionProps(
                    question=question, name=prop,
                    value=q['question']['props'][prop]
                ).save()

        for r in q['question']['responses']:
            response = Response(
                owner=user,
                question=question,
                title=clean_lang_dict(r['title']),
                score=r['score'],
                order=r['order']
            )
            response.save()
            r['id'] = response.pk

            for prop in r['props']:
                if prop != 'id':
                    ResponseProps(
                        response=response, name=prop,
                        value=r['props'][prop]
                    ).save()
Пример #21
0
    def post(self, request, *args, **kwargs):
        file = request.data['myFile']
        file_name = default_storage.save(file.name, file)
        parsed_pdf = parser.from_file(file_name)
        data = re.sub('[^a-zA-Z0-9-_*. ?:()!]', '', parsed_pdf['content'])
        logger.error(data)
        quiz = Quiz(name=data[slicer(data, "docx"):data.index("1)")] +
                    "- Sample")
        quiz.save()
        data = data[data.index("1)"):]

        blocks = re.split(r'[ ](?=[0-9]+\))', data)

        question_num = int(len(blocks) / 2)
        for i, elem in enumerate(blocks[:question_num]):
            if ("ANSWER KEY" in elem):
                elem = elem[:elem.index("ANSWER KEY")]
            question = elem[:elem.index("A)")]

            q = Question(label=question,
                         quiz=quiz,
                         order=int(question[:question.index(")")]))
            q.save()
            letters = ["A", "B", "C", "D"]
            for index, char in enumerate(letters):
                label = ""
                if index == len(letters) - 1:
                    label = elem[elem.index(char + ")"):]
                else:
                    label = elem[elem.index(char +
                                            ")"):elem.index(letters[index +
                                                                    1] + ")")]
                Answer.objects.create(
                    question=q,
                    label=label,
                    is_correct=blocks[question_num + i].find(char) > -1)

        return Response(QuizListSerializer(quiz).data)
    for line_number, line in enumerate(data):
        line = line.split('\t')
        if line[0] == '':
            continue
        if line[1].startswith('id: +'):
            quiz_title = line[0]
            current_quiz = Quiz(user_id=1,
                                category='not set',
                                difficulty=1,
                                description='No description')
            current_quiz.name = quiz_title
            current_quiz.save()
            continue
        quiz_question = line[0]
        question_list = []
        current_question = Question(quiz=current_quiz, text=quiz_question)
        current_question.save()
        question_list.append(current_question)
        answer_list = []
        for it, answer in enumerate(line[1:]):
            if answer == '':
                is_result = True
                for correct in [l for l in line[it + 3:] if l != '\n']:
                    good_answer = correct
                    for ans in answer_list:
                        if ans.text == good_answer:
                            ans.is_correct = True
                            ans.save()

                for q in question_list:
                    q.quiz = current_quiz
Пример #23
0
def add_questions(request, quizid):

    user = request.user
    if user.is_admin():

        quiz = Quiz.objects.get(quiz_id=quizid)

        if request.method == 'POST':

            q_type = strip_tags(request.POST.get('type'))
            ques = Question()
            ques.quiz = quiz
            ques.type = strip_tags(request.POST.get('type'))
            ques.marks = strip_tags(request.POST.get('marks'))
            ques.level = strip_tags(request.POST.get('level'))
            ques.time_limit = strip_tags(request.POST.get('time_limit'))
            ques.question = strip_tags(request.POST.get('question'))
            ques.negative = strip_tags(request.POST.get('negative'))

            # if Image is uploaded
            img = request.FILES.get('image')
            if img:

                ques.image = img
            else:
                print("\n\n\n\nNo File was uploaded\n\n\n\n")

            # if Code is added
            code = request.POST.get('code')
            if code:
                ques.code = code

            # if Question is subjective
            if q_type == 's':
                ques.subjective_answer = strip_tags(
                    request.POST.get('subjective_answer'))

            # Question is objective
            else:
                ques.option_A = strip_tags(request.POST.get('option_a'))
                ques.option_B = strip_tags(request.POST.get('option_b'))
                ques.option_C = strip_tags(request.POST.get('option_c'))
                ques.option_D = strip_tags(request.POST.get('option_d'))
                ques.correct = strip_tags(request.POST.get('correct'))

            ques.save()
            return JsonResponse({'kudos': "kudos"})

        # GET the page
        else:
            return render(request, 'add_questions.html', {
                'title': 'Add Questions',
                'quiz_data': quiz
            })
    # User Does not has sufficient permissions
    else:

        messages.info(
            request,
            'You do not have the permissions required to edit this quiz')
        return redirect('home')
Пример #24
0
    def test_question_title_no_quiz_props(self):
        question = Question(title='{"fi": "kysymykseni"}')
        question.save()

        self.assertEqual("kysymykseni", question.get_title('fi'))
        self.assertEqual("kysymykseni", str(question))
Пример #25
0
def home_page(request):
    new_item_text = Question(question_text='item_text')
    return render(request, 'home.html', {
        'new_item_text': request.POST.get('item_text', ''),
    })
Пример #26
0
 def update(self, instance, validated_data, user=None):
     question = Question(id=instance.id, **validated_data)
     question.save()
     return question
Пример #27
0
 def test_string_representation(self):
     question = Question(text='question text')
     assert str(question) == question.text