コード例 #1
0
ファイル: test_forms.py プロジェクト: vital101/quiztacular
class QuizSelectFormTestCase(TestCase):

    def setUp(self):
        self.quiz = Quiz(
            name='Test Quiz',
            slug='Test Quiz',
            description=''
        )
        self.quiz.save()

        self.question_a = Question(question='Test Question A', correct_answer='Yes')
        self.question_a.save()
        self.question_b = Question(question='Test Question B', correct_answer='No')
        self.question_b.save()

        self.quiz.questions.add(self.question_a)
        self.quiz.questions.add(self.question_b)

    def test_new_quiz_result_created_on_save(self):
        quiz_select_form = QuizSelectForm(data={ 'quiz': self.quiz.id, 'name': 'J Doe'})
        self.assertEqual(0, QuizResult.objects.count())
        quiz_select_form.is_valid()
        quiz_select_form.save()

        quiz_results = QuizResult.objects.filter(name='J Doe', quiz=self.quiz)
        self.assertEqual(1, len(quiz_results))
コード例 #2
0
ファイル: tests.py プロジェクト: a5720128a/test2quiz
    def test_saving_and_retrieving_users(self):

        quiz_ = Quiz()
        quiz_.save()

        first_user = User()
        first_user.user_text = 'The first (ever) quiz user'
        first_user.quiz2 = quiz_
        first_user.save()

        second_user = User()
        second_user.user_text = 'user the second'
        second_user.quiz2 = quiz_
        second_user.save()

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

        saved_users = User.objects.all()
        self.assertEqual(saved_users.count(), 2)

        first_saved_user = saved_users[0]
        second_saved_user = saved_users[1]
        self.assertEqual(first_saved_user.user_text,
                         'The first (ever) quiz user')
        self.assertEqual(first_saved_user.quiz2, quiz_)
        self.assertEqual(second_saved_user.user_text, 'user the second')
        self.assertEqual(second_saved_user.quiz2, quiz_)
コード例 #3
0
ファイル: views.py プロジェクト: aats0123/quiz_project
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
ファイル: tests.py プロジェクト: a5720128a/test2quiz
    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_)
コード例 #5
0
ファイル: test_views.py プロジェクト: vital101/quiztacular
 def test_context_contains_quiz_select_form(self):
     test_quiz = Quiz(
         name='Test Quiz',
         slug='Test Quiz',
         description='A great test quiz'
     )
     test_quiz.save()
     response = self.client.get(reverse('home'))
     self.assertTrue(response.context['has_quizzes'])
     self.assertIsNot(None, response.context['form'])
コード例 #6
0
ファイル: views.py プロジェクト: iustitia/garts
def make_quiz(request, random=True, count=10):
    name = uuid.uuid4().hex[:10]
    q = Quiz(title=name, url=name, category=Category.objects.first(), random_order=True, answers_at_end=True, exam_paper=True, single_attempt=True)
    q.save()
    count = int(count)
    questions = [randint(1,170) for _ in range(count)]
    q.question_set = questions
    out = redirect('/quiz/' + name + '/take/')

    return out
コード例 #7
0
ファイル: tests.py プロジェクト: a5720128a/test2quiz
    def test_render_after_submit(self):
        quiz_ = Quiz()
        quiz_.save()

        user_ = User()
        user_.user_text = 'test'
        user_.user_point += 1
        user_.quiz2 = quiz_
        user_.save()

        response = self.client.post('/%d/submit' % (quiz_.id, ),
                                    data={'user_input': 'A new user'})
コード例 #8
0
ファイル: test_forms.py プロジェクト: vital101/quiztacular
class QuizFormTestCase(TestCase):

    def setUp(self):
        self.quiz = Quiz(
            name='Test Quiz',
            slug='Test Quiz',
            description=''
        )
        self.quiz.save()

        self.question_a = Question(question='Test Question A', correct_answer='Yes')
        self.question_a.save()
        self.question_b = Question(question='Test Question B', correct_answer='No')
        self.question_b.save()

        self.quiz.questions.add(self.question_a)
        self.quiz.questions.add(self.question_b)

        self.quiz_result = QuizResult(name='J Doe', quiz=self.quiz)
        self.quiz_result.save()

        self.data = {}
        for answer in self.quiz_result.answers.all():
            question_text = answer.question.question
            self.data['question_{0}'.format(answer.id)] = 'Yes'

    def test_questions_are_populated_and_required(self):
        quiz_form = QuizForm(blank_answers=self.quiz_result.answers.all(),
                             data=self.data)
        self.assertEqual(2, len(quiz_form.fields))
        for key in quiz_form.fields.iterkeys():
            self.assertTrue(quiz_form.fields[key].required)

    def test_questions_marked_as_answered_on_save(self):
        quiz_form = QuizForm(blank_answers=self.quiz_result.answers.all(),
                             data=self.data)
        quiz_form.is_valid()
        quiz_form.save(self.quiz_result)

        # Note: an unanswered question is represented by None
        answers = self.quiz_result.answers.all()
        for answer in answers:
            self.assertNotEqual(None, answer.correct)

    def test_quiz_completed_datetime_set_on_save(self):
        quiz_form = QuizForm(blank_answers=self.quiz_result.answers.all(),
                             data=self.data)
        quiz_form.is_valid()

        self.assertEqual(None, self.quiz_result.completed)
        quiz_form.save(self.quiz_result)
        self.assertNotEqual(None, self.quiz_result.completed)
コード例 #9
0
def quizcreation(request):
    # Récupère les données du quiz depuis le bouton quizData
    context = {}
    data = request.POST.get("quizData")
    if data != None:
        data = json.loads(data)
        context["quiz"] = data

        # Création des propriétés pour la sauvegarde dans la base de données
        quizTitle = data["quesTitle"]
        quiz = Quiz(title=quizTitle, data=data, user_id=1)
        quiz.save()

    return render(request, "quiz-creation.html", context)
コード例 #10
0
ファイル: vconcept.py プロジェクト: kartikshah1/Test
 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)
コード例 #11
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)
コード例 #12
0
def catalog(request):
    empty_fields = user_profile_setup_progress(request.user)
    if empty_fields > 0:
        messages.add_message(
            request, messages.INFO,
            f"Finish setting up your profile <a href={reverse('settings')}> here</a>. You have {empty_fields} fields to fill."
        )
        return redirect(reverse('settings'))

    return render(
        request, 'main/catalog.html', {
            'competitions':
            Competition.objects.filter(active=True).order_by('-created_on'),
            'workshops':
            Workshop.objects.filter(active=True).order_by('-created_on'),
            'quizzes':
            Quiz.objects.filter(active=True).order_by('-created_on'),
            'classes':
            OneOnOneClass.objects.filter(active=True).order_by('-created_on'),
            'new_competitions':
            Competition.get_recent(),
            'new_quizzes':
            Quiz.get_recent(),
            'new_workshops':
            Workshop.get_recent(),
        })
コード例 #13
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
コード例 #14
0
ファイル: views.py プロジェクト: jirawatsaesu/Test29
def quiz_page(request):
    if request.method == 'POST':
        ques = request.POST.get('quiz')
        ans = request.POST.get('answer')
        Quiz(question=ques, answer=ans).save()
        return redirect('/quiz/')
    return render(request, 'quiz.html')
コード例 #15
0
def import_quiz_camtasia8(con_file, video):
    """
    Doc
    """
    #tree = ET.parse(fname)
    tree = ET.fromstring(con_file.read())
    rdf = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}'
    tscIQ = '{http://www.techsmith.com/xmp/tscIQ/}'
    xmpDM = '{http://ns.adobe.com/xmp/1.0/DynamicMedia/}'
    quiz_xpath = ".//" + rdf + "Description[@" + tscIQ + "questionSetName]"

    for quiz in tree.findall(quiz_xpath):
        title = quiz.attrib[tscIQ + "questionSetName"]
        startTime = int(
            math.floor(float(quiz.attrib[xmpDM + "startTime"]) / 1000))
        question_xpath = ".//" + rdf + "Description[@" + tscIQ + "id]"

        quiz_obj = Quiz(title=title)
        quiz_obj.save()
        try:
            marker = QuizMarker(video=video, time=startTime, quiz=quiz_obj)
            marker.save()
            qmodule_obj = QuestionModule(title='Dummy Title',
                                         quiz=quiz_obj,
                                         dummy=True)
            qmodule_obj.save()

        except Exception, e:
            quiz_obj.delete()

            try:
                marker = QuizMarker.objects.get(video=video, time=startTime)
                quiz_obj = marker.quiz
                qmodule_obj = QuestionModule.objects.filter(quiz=quiz_obj)[0]
                if (qmodule_obj.dummy):
                    qmodule_obj.dummy = False
                    qmodule_obj.title = quiz_obj.title
                    qmodule_obj.save()
                    quiz_obj.title = "Quiz : Multiple Questions"
                    quiz_obj.save()
                qmodule_obj = QuestionModule(title=title,
                                             quiz=quiz_obj,
                                             dummy=False)
                qmodule_obj.save()

            except Exception, e:
                marker = None
                print "Some other error in marker creation at %d, %d" % (
                    startTime, video.id)
                print(e)
コード例 #16
0
def create_quiz(user, quiz_obj, act_xml):

    quiz = Quiz()
    quiz.owner = user
    quiz.title = quiz_obj['title']
    quiz.description = quiz_obj['description']
    quiz.save()

    # save gamification events
    if act_xml.getElementsByTagName('gamification')[:1]:
        events = parse_gamification_events(
            act_xml.getElementsByTagName('gamification')[0])
        # remove anything existing for this course
        QuizGamificationEvent.objects.filter(quiz=quiz).delete()
        # add new
        for event in events:
            e = QuizGamificationEvent(user=user,
                                      quiz=quiz,
                                      event=event['name'],
                                      points=event['points'])
            e.save()

    quiz_obj['id'] = quiz.pk

    # add quiz props
    create_quiz_props(quiz, quiz_obj)

    # add quiz questions
    create_quiz_questions(user, quiz, quiz_obj)

    return json.dumps(quiz_obj)
コード例 #17
0
ファイル: views.py プロジェクト: rozap/discountrates
def quiz(request):
    if request.method == 'POST':
        session = str(uuid.uuid4())
        validator = QuizValidator(json.loads(request.body))
        valid, data = validator.validate()

        if not valid:
            return (data, 400)
        quiz = Quiz(
            session = session, 
            expected_return = data['expected_return'],
            expected_life = data['expected_life'],
            save_priority = data['save_priority'],
            net_worth = data['net_worth']
            )
        quiz.save()
        return quiz
    return { 'hi' : ':)'}
コード例 #18
0
    def save(self, *args, **kwargs):
        self.slug = slugify(unicode(self.title))
        self.slug = self.slug[:49]
        super(Lesson, self).save(*args, **kwargs)

        if not self.sections.all():
            section = LessonSection(content_type='topic', lesson=self)
            section.save()
            section = LessonSection(content_type='media', lesson=self)
            section.save()
            section = LessonSection(content_type='reading', lesson=self)
            section.save()
            section = LessonSection(content_type='apply', lesson=self)
            section.save()

        if not self.lesson_discussion.all():
            try:
                user = self.creator
            except:
                user = User.objects.filter(is_superuser=True)[0]
            try:
                thread = Post(text="Start a discussion!",
                              creator=user,
                              subject=self.title + ' Talk',
                              parent_post=None)
                thread.save()
                discussion = LessonDiscussion(thread=thread, lesson=self)
                discussion.save()
            except:
                pass  # Fail silently...

        if not self.lesson_quiz.all():

            try:
                title = '%s Quiz' % (self.title)
                quiz = Quiz(title=title,
                            url=title,
                            random_order=False,
                            answers_at_end=True)
                quiz.save()
                lesson_quiz = LessonQuiz(quiz=quiz, lesson=self)
                lesson_quiz.save()
            except Exception as e:
                pass  # Fail silently...
コード例 #19
0
    def get_queryset(self):
        user = self.kwargs['user_id']

        # check permissions, get_user raises PermissionDenied
        get_user(self.request, user)

        quizzes = Quiz.get_by_activity_type(Activity.FEEDBACK)
        return QuizAttempt.objects \
            .filter(user__pk=user, quiz__in=quizzes) \
            .order_by('-submitted_date', '-attempt_date')
コード例 #20
0
ファイル: views.py プロジェクト: kartikshah1/Test
def import_quiz_camtasia8(con_file, video):
    """
    Doc
    """
    #tree = ET.parse(fname)
    tree = ET.fromstring(con_file.read())
    rdf = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}'
    tscIQ = '{http://www.techsmith.com/xmp/tscIQ/}'
    xmpDM = '{http://ns.adobe.com/xmp/1.0/DynamicMedia/}'
    quiz_xpath = ".//" + rdf + "Description[@" + tscIQ + "questionSetName]"

    for quiz in tree.findall(quiz_xpath):
        title = quiz.attrib[tscIQ + "questionSetName"]
        startTime = int(math.floor(float(quiz.attrib[xmpDM + "startTime"])/1000))
        question_xpath = ".//" + rdf + "Description[@" + tscIQ + "id]"

        quiz_obj = Quiz(title=title)
        quiz_obj.save()
        try:
            marker = QuizMarker(video=video, time=startTime, quiz=quiz_obj)
            marker.save()
            qmodule_obj = QuestionModule(
                title='Dummy Title',
                quiz=quiz_obj,
                dummy=True
            )
            qmodule_obj.save()

        except Exception, e:
            quiz_obj.delete()

            try:
                marker = QuizMarker.objects.get(video=video, time=startTime)
                quiz_obj = marker.quiz
                qmodule_obj = QuestionModule.objects.filter(quiz=quiz_obj)[0]
                if(qmodule_obj.dummy):
                    qmodule_obj.dummy = False
                    qmodule_obj.title = quiz_obj.title
                    qmodule_obj.save()
                    quiz_obj.title = "Quiz : Multiple Questions"
                    quiz_obj.save()
                qmodule_obj = QuestionModule(
                    title=title,
                    quiz=quiz_obj,
                    dummy=False
                )
                qmodule_obj.save()

            except Exception,e:
                marker = None
                print "Some other error in marker creation at %d, %d" %(startTime, video.id)
                print(e)
コード例 #21
0
ファイル: tests.py プロジェクト: jirawatsaesu/Test29
    def test_answer_question_and_points_collect(self):
        first_question = Quiz()
        first_question.question = '2+2*0+1=1'
        first_question.answer = False
        first_question.wrong_ans = 0
        first_question.correct_ans = 0
        first_question.save()

        # 2 correct answer
        first_question.correct_ans += 1
        first_question.correct_ans += 1

        # 1 wrong answer
        first_question.wrong_ans += 1

        first_question.save()
        saved_question = Quiz.objects.first()

        self.assertEqual(saved_question.correct_ans, 2)
        self.assertEqual(saved_question.wrong_ans, 1)
コード例 #22
0
ファイル: views.py プロジェクト: eschlecht123/djangotest
def homepage(request):

    q_obj = Quiz(pk=6)
    myList = []

    for i in (Quiz.objects.all()):
        myList.append(i)

    quiz_id = myList[random.randint(0, len(myList))].id

    return HttpResponseRedirect('quiz/%s/answer_quiz/' % quiz_id)
コード例 #23
0
    def create(self, validated_data):
        name            = validated_data.get('name')
        duration        = validated_data.get('duration')
        start_time      = validated_data.get('start_time')
        end_time        = validated_data.get('end_time')
        max_attempts    = validated_data.get('max_attempts')
        classroom       = validated_data.get('classroom')
        owner           = validated_data.get('owner')

        instance = Quiz(
            classroom = classroom,
            owner = owner,
            name = name,
            duration = duration,
            start_time = start_time,
            end_time = end_time,
            max_attempts = max_attempts,
        )
        instance.save()
        return instance
コード例 #24
0
ファイル: test_views.py プロジェクト: vital101/quiztacular
class QuizTestCase(TestCase):

    def setUp(self):
        self.quiz = Quiz(
            name='Test Quiz',
            slug='Test Quiz',
            description='Test Quiz'
        )
        self.quiz.save()

        self.question_a = Question(question='Test Question A', correct_answer='Yes')
        self.question_a.save()
        self.question_b = Question(question='Test Question B', correct_answer='No')
        self.question_b.save()

        self.quiz.questions.add(self.question_a)
        self.quiz.questions.add(self.question_b)

    def test_should_404_if_quiz_doesnt_exist(self):
        response = self.client.get(reverse('quiz', args=(111,)))
        self.assertEqual(404, response.status_code)

    def test_should_redirect_home_if_quiz_is_taken(self):
        quiz_result = QuizResult(
            name='John Doe',
            quiz=self.quiz,
            completed=timezone.now()
        )
        quiz_result.save()
        response = self.client.get(reverse('quiz', args=(quiz_result.id,)))
        self.assertEqual(302, response.status_code)

    def test_should_contain_form_in_context(self):
        quiz_result = QuizResult(
            name='John Doe',
            quiz=self.quiz
        )
        quiz_result.save()
        response = self.client.get(reverse('quiz', args=(quiz_result.id,)))
        self.assertEqual(200, response.status_code)
        self.assertIsNot(None, response.context['form'])
コード例 #25
0
    def get_queryset(self, *args, **kwargs):
        #queryset = Quiz.objects.filter(roll_out = True)
        queryset = Quiz.objectsfilter(roll_out=True).exclude(
            quiztaker__user=self.request.user)
        query = self.request.GET.get("q")

        if query:
            queryset = queryset.filter(
                Q(name__icontains=query)
                | Q(description__icontains=query)).distinct()

        return queryset
コード例 #26
0
    def handle(self, *args, **options):
        Quiz.objects.all().delete()
        Options.objects.all().delete()

        if not options['path']:
            self.stderr.write(
                self.style.ERROR(
                    "Please provide a valid path to a JSON Formatted Question File"
                ))

        filepath = ''.join(options['path'])
        filepath = filepath.replace('\u202a', '')
        print(filepath)

        with open(filepath, "r", encoding="utf-8") as sql_data:
            data = json.loads(sql_data.read())
            question_list = data['questions']
            for question in question_list:
                tempQuestion = Quiz(question=question['question'])
                tempQuestion.save()
                index = question['correct']  # Int / Array
                if type(index) == int:
                    index = [index]
                for option_index, option in enumerate(question['options']):
                    temp = Options(option=option,
                                   is_correct=option_index in index)
                    temp.save()
                    tempQuestion.answers.add(temp)

                tempQuestion.save()

        self.stdout.write(
            self.style.SUCCESS('Successfully loaded all Elements'))
コード例 #27
0
def create_quiz(user, quiz_obj, act_xml):

    quiz = Quiz()
    quiz.owner = user
    quiz.title = quiz_obj['title']
    quiz.description = quiz_obj['description']
    quiz.save()

    # save gamification events
    if act_xml.getElementsByTagName('gamification')[:1]:
        events = parse_gamification_events(act_xml.getElementsByTagName('gamification')[0])
        # remove anything existing for this course
        QuizGamificationEvent.objects.filter(quiz=quiz).delete()
        # add new
        for event in events:
            e = QuizGamificationEvent(user=user, quiz=quiz, event=event['name'], points=event['points'])
            e.save()

    quiz_obj['id'] = quiz.pk

    # add quiz props
    create_quiz_props(quiz, quiz_obj)

    # add quiz questions
    create_quiz_questions(user, quiz, quiz_obj)

    return json.dumps(quiz_obj)
コード例 #28
0
ファイル: test_models.py プロジェクト: osx11/MagicQuiz
class TestModels(TestCase):
    def setUp(self):
        self.quiz = Quiz(name='TestQuiz',
                         expires=strptime('2100-01-01 00:00:00'))
        self.quiz.save()

    def testQuizExpires(self):
        self.assertFalse(self.quiz.is_expired())

        self.quiz.expires = strptime('3150-05-10 17:06:00')
        self.quiz.save()

        self.assertFalse(self.quiz.is_expired())

        self.quiz.expires = strptime('1980-01-02 12:12:12')
        self.quiz.save()

        self.assertTrue(self.quiz.is_expired())

        self.quiz.expires = strptime('1980-01-02 12:12:12')

        self.assertTrue(self.quiz.is_expired())
コード例 #29
0
def create_quiz(user, quiz_obj):
    quiz = Quiz()
    quiz.owner = user
    quiz.title = clean_lang_dict(quiz_obj['title'])
    quiz.description = clean_lang_dict(quiz_obj['description'])
    quiz.save()

    # add quiz questions
    create_quiz_questions(user, quiz, quiz_obj)

    return quiz
コード例 #30
0
ファイル: models.py プロジェクト: llcit/nflrc-pbll-dev
    def save(self, *args, **kwargs):
        self.slug = slugify(unicode(self.title))
        self.slug = self.slug[:49]
        super(Lesson, self).save(*args, **kwargs)

        if not self.sections.all():
            section = LessonSection(content_type='topic', lesson=self)
            section.save()
            section = LessonSection(content_type='media', lesson=self)
            section.save()
            section = LessonSection(content_type='reading', lesson=self)
            section.save()
            section = LessonSection(content_type='apply', lesson=self)
            section.save()

        if not self.lesson_discussion.all():
            try:
                user = self.creator
            except:
                user = User.objects.filter(is_superuser=True)[0]
            try:
                thread = Post(text="Start a discussion!", creator=user, subject=self.title+' Talk', parent_post=None)
                thread.save()
                discussion = LessonDiscussion(thread=thread, lesson=self)
                discussion.save()
            except:
                pass  # Fail silently...

        if not self.lesson_quiz.all():
            
            try:
                title = '%s Quiz'% (self.title)
                quiz = Quiz(title=title, url=title, random_order=False, answers_at_end=True)
                quiz.save()
                lesson_quiz = LessonQuiz(quiz=quiz, lesson=self)
                lesson_quiz.save()
            except Exception as e:
                pass  # Fail silently...
コード例 #31
0
def create_new_quiz(request):
    """
    Creates a new quiz and its default settings for the given request, and returns the quiz.
    """
    quiz = Quiz()  #New Quiz is created
    quiz.resourceLinkId = lti.get_resource_link_id(request)
    quiz.consumer_key = lti.get_oauth_consumer_key(request)
    quiz.contextId = lti.get_context_id(request)
    quiz.save()  #Save the Quiz
    quizSettings = QuizSettings(quiz=quiz)
    quizSettings.save()
    return quiz
コード例 #32
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)
コード例 #33
0
ファイル: test_quiz.py プロジェクト: mrhattyhat/PyQuiz
    def setup_method(self, test_method):
        username = '******'
        quiz_title = u'PyTest Quiz'

        try:
            u = User.objects.get(username=username)
        except User.DoesNotExist:
            u = User(username=username, first_name='Test', last_name='User')
            u.set_password('testuserpass')
            u.save()

        try:
            q = Quiz.objects.get(title=quiz_title)
        except Quiz.DoesNotExist:
            q = Quiz(title=quiz_title, instruction='PyTest creating a quiz', quiz_type=1)
            q.save()

        self.user = u
        self.quiz = q
        self.quiz_title = quiz_title
        self.username = username

        self._create_questions()
コード例 #34
0
ファイル: test_forms.py プロジェクト: vital101/quiztacular
    def setUp(self):
        self.quiz = Quiz(
            name='Test Quiz',
            slug='Test Quiz',
            description=''
        )
        self.quiz.save()

        self.question_a = Question(question='Test Question A', correct_answer='Yes')
        self.question_a.save()
        self.question_b = Question(question='Test Question B', correct_answer='No')
        self.question_b.save()

        self.quiz.questions.add(self.question_a)
        self.quiz.questions.add(self.question_b)
コード例 #35
0
    def create_quizzes(self, n: int, categories: list, users: list) -> None:
        quizzes = []
        date_before = timezone.now()

        for i in range(n):
            category = random.choice(categories)
            user = random.choice(users)
            quizzes.append(Quiz(
                name=f"{self.faker.sentence()}{i}",
                creator=user,
                category=category,
                date_published=timezone.now() if random.random() > 0.5 else None
            ))
        Quiz.objects.bulk_create(quizzes)
        for quiz in Quiz.objects.filter(date_created__gt=date_before):
            self.create_questions_to_quiz(quiz)
コード例 #36
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
コード例 #37
0
ファイル: models.py プロジェクト: pixyj/feel
    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
コード例 #38
0
ファイル: store.py プロジェクト: IshanManchanda/sorobrain
def catalog(request):
    return render(
        request, 'main/catalog.html', {
            'competitions':
            Competition.objects.filter(active=True).order_by('-created_on'),
            'workshops':
            Workshop.objects.filter(active=True).order_by('-created_on'),
            'quizzes':
            Quiz.objects.filter(active=True).order_by('-created_on'),
            'classes':
            OneOnOneClass.objects.filter(active=True).order_by('-created_on'),
            'new_competitions':
            Competition.get_recent(),
            'new_quizzes':
            Quiz.get_recent(),
            'new_workshops':
            Workshop.get_recent(),
        })
コード例 #39
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
コード例 #40
0
ファイル: models.py プロジェクト: pixyj/feel
    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
コード例 #41
0
def create_quiz(req, user, quiz_obj, act_xml, activity=None):

    quiz = Quiz()
    quiz.owner = user
    quiz.title = quiz_obj['title']
    quiz.description = quiz_obj['description']
    quiz.save()

    quiz_obj['id'] = quiz.pk

    # add quiz props
    create_quiz_props(quiz, quiz_obj)

    # add quiz questions
    create_quiz_questions(user, quiz, quiz_obj)

    return json.dumps(quiz_obj)
コード例 #42
0
ファイル: test_forms.py プロジェクト: vital101/quiztacular
    def setUp(self):
        self.quiz = Quiz(
            name='Test Quiz',
            slug='Test Quiz',
            description=''
        )
        self.quiz.save()

        self.question_a = Question(question='Test Question A', correct_answer='Yes')
        self.question_a.save()
        self.question_b = Question(question='Test Question B', correct_answer='No')
        self.question_b.save()

        self.quiz.questions.add(self.question_a)
        self.quiz.questions.add(self.question_b)

        self.quiz_result = QuizResult(name='J Doe', quiz=self.quiz)
        self.quiz_result.save()

        self.data = {}
        for answer in self.quiz_result.answers.all():
            question_text = answer.question.question
            self.data['question_{0}'.format(answer.id)] = 'Yes'
コード例 #43
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
コード例 #44
0
ファイル: test_models.py プロジェクト: osx11/MagicQuiz
 def setUp(self):
     self.quiz = Quiz(name='TestQuiz',
                      expires=strptime('2100-01-01 00:00:00'))
     self.quiz.save()