def newQuiz(): available_posts = db.session.query(Article).all() post_list = [(i.id, i.name) for i in available_posts] form = QuizForm() form.help_link.choices = post_list if form.validate_on_submit(): question = Quiz(question=form.question.data, answer1=form.answer1.data, answer2=form.answer2.data, answer3=form.answer3.data) if form.good_answer.data == 'Odpowiedź 1': question.good_answer = form.answer1.data elif form.good_answer.data == 'Odpowiedź 2': question.good_answer = form.answer2.data elif form.good_answer.data == 'Odpowiedź 3': question.good_answer = form.answer3.data question.help_link = form.help_link.data db.session.add(question) db.session.commit() flash('Dodano nowe pytanie!', 'success') return redirect(url_for('handle_articles')) return render_template('newQuiz.html', title='Nowy artykuł', form=form, legend='Nowy artykuł', categories=GetAllCategories())
def add_quiz(request): """Add the new quiz that superuser created to the database.""" form = QuizForm(request.POST) if form.is_valid(): new_quiz = form.save() new_quiz.save() return HttpResponseRedirect('/create_quiz/') else: return render(request, 'invalidAttempt.html', {'message': 'Invalid input!'})
def quizsetup(): global questions global definition global choices global answer global score global count global no score = 0 count = 0 answer = 0 form = QuizForm() # if request.method == 'POST': # try: # no = form.no_of_questions.data # except: # message = f"Do you really think {request.form['answer']} is a valid response?" # return render_template('quizsetup.html') # if not no > 0: # return f''' # <html> # <body> # <p>How many questions?</p> # <form method='POST' action='/quizsetup'> # <p><input name='answer' /></p> # <p><input type='submit' value='Start'/></p> # </form> # <p>Do you really think {request.form['answer']} is a valid response?</p> # </body> # </html> # ''' # questions = generate_questions(no) # definition = get_definition(questions[0]) # choices = generate_choices(definition) # return redirect('/quiz') if form.validate_on_submit(): flash(f'Quiz generated with {form.no_of_questions.data} Questions') no = form.no_of_questions.data questions = generate_questions(no) definition = get_definition(questions[0]) choices = generate_choices(definition) return redirect(url_for('quiz')) # return f''' # <html> # <body> # <p>{choices}</p> # </body> # </html> # ''' return render_template('quizsetup.html', title='Quiz Setup', form=form, user=user)
def categorywise(category): categoryList = [ 'math', 'pop_culture', 'history', 'sports', 'business', 'tech', 'geography', 'other', ] if category in categoryList: form = QuizForm() if current_user.answered is None: current_user.answered = dumps([]) db.session.commit() alreadyAns = loads(current_user.answered) #Check the questions to display questions_to_display = Questions.query.filter( Questions.creatorid != str(current_user.id)).filter( ~Questions.questionid.in_(alreadyAns)).filter( Questions.category == category).all() if len(questions_to_display) is 0: flash( "We're so sorry but it seems that there are no questions on this topic" ) return render_template('quiz.html', questions_to_display=questions_to_display, form=form, users=getStandings()) else: form = QuizForm() if current_user.answered is None: current_user.answered = dumps([]) db.session.commit() alreadyAns = loads(current_user.answered) #Check the questions to display questions_to_display = Questions.query.filter( Questions.creatorid != str(current_user.id)).filter( ~Questions.questionid.in_(alreadyAns)).all() flash('Please enter a url where the category is any one of' + str(categoryList)) return redirect( url_for('quiz.html', questions_to_display=questions_to_display, form=form, users=getStandings()))
def post(self, request, **kwargs): form = QuizForm(self.through, request.POST) results = form.get_response() form.check_self_boxes() points, gold = self.quiz.calculate_reward(results) self.through.set_played(results, points, gold) grade = float(points) / self.quiz.points_reward * 10 return render_to_response('quiz/result.html', {'quiz': self.quiz, 'points': points, 'grade': grade}, context_instance=RequestContext(request))
def start_test(exams=0): form = QuizForm() print "request===== examps=========", request, request.form, exams if not current_user.is_admin: already_submit = UserQuestionAnswer.query.filter_by( user_id=int(current_user.id)).first() print("already_submit", already_submit) if already_submit: flash("Sorry!You have already submitted the test.") return redirect(url_for('open_login')) # for each in Questions.query.all(): # form.question = (each.id,each.question) # form.answers.choices = [(probot.id, probot.choice) for probot in each.questions_choices] # return render_template('quiz.html', form=form,questions = Questions.query.all()) # print "form>>>>>>>>>>data",form questions = Questions() print("exams===========", exams, type(exams)) if current_user.is_admin: questions = Questions.query.all() else: questions = Questions.query.filter_by(exam_id=exams).all() print("questions===========", questions) return render_template('quiz.html', form=form, questions=questions, name=current_user.username)
def make_quiz(request): """Shows all current quizes and lets users make new ones""" quizzes = Quiz.objects.all() if request.method == "POST": # copies form data to a new dictionary and adds the user as author data = request.POST data_copy = dict() for key, value in data.iteritems(): data_copy[key] = value data_copy['author'] = request.user.id form = QuizForm(data_copy) if form.is_valid(): form.save(request.user) return HttpResponseRedirect('/quiz/new') else: form = QuizForm() return render(request, 'quiz/make_quiz.html', context={'form': form, 'quizzes': quizzes})
def create_quiz(request): """For superuser to create new quizzes.""" if (request.user.is_superuser): form = QuizForm() quizzes = Quiz.objects.order_by('name') return render(request, 'createQuiz.html', { 'form': form, 'lists': quizzes }) else: return render(request, 'invalidAttempt.html', {'message': 'You are not a super user!'})
def quiz(request): if 'uid' not in request.session: return redirect('login') user = User.objects.get(id=request.session['uid']) if user.stage == 'quiz_started': if request.method == "GET": quizForm = QuizForm() return render(request, 'core/quiz.html', {'quizForm': quizForm}) elif request.method == "POST": quizForm = QuizForm(request.POST, request.FILES) if quizForm.is_valid(): quiz = quizForm.save(commit=False) quiz.work_eligible = request.POST['work_eligible'] == 'Yes' quiz.save() user.quiz = quiz user.stage = 'quiz_completed' now = datetime.datetime.now() user.quiz_completed_date = now user.latest_change = now user.save() else: return render(request, 'core/quiz.html', {'quizForm': quizForm, 'errors': quizForm.errors}) return redirect('decider')
def quizCreate(request, department, class_number, year, semester, section): user = request.user c = getClassObject(department, class_number, year, semester, section, user) quizzes = Quiz.objects.filter(cid=c.cid) if request.method == 'POST': quiz = Quiz(cid=c) form = QuizForm(request.POST, instance=quiz) if form.is_valid(): form.save() url = getClassUrl(c) + 'instructor/quiz/create/' return HttpResponseRedirect("") else: form = QuizForm() content = getContent(c, user) content['form'] = form content['quizzes'] = quizzes return render_to_response('instructor/quizCreate.html', content, context_instance=RequestContext(request))
def quizUpdate(request, department, class_number, year, semester, section, qid): user = request.user c = getClassObject(department, class_number, year, semester, section, user) q = get_object_or_404(Quiz, pk=qid) quizzes = Quiz.objects.filter(cid=c.cid) if request.method == 'POST': form = QuizForm(request.POST) if form.is_valid(): Quiz.objects.filter(id=q.id).update(name=form.cleaned_data["name"], start_date=form.cleaned_data["start_date"], end_date=form.cleaned_data["end_date"], student_attempts=form.cleaned_data["student_attempts"]) url = getClassUrl(c) + 'instructor/quiz/create/' return HttpResponseRedirect(url) else: form = QuizForm(initial={'name': q.name, 'start_date': q.start_date, 'end_date': q.end_date, 'student_attempts': q.student_attempts} ) content = getContent(c, user) content['form'] = form content['quizzes'] = quizzes return render_to_response('instructor/quizCreate.html', content, context_instance=RequestContext(request))
def get(self, request, *args, **kwargs): self.through.make_questions() form = QuizForm(self.through) if self.through.is_not_running: self.through.set_running() seconds_left = self.through.time_left return render_to_response('quiz/quiz.html', {'quiz': self.quiz, 'form': form, 'seconds_left': seconds_left}, context_instance=RequestContext(request))
def create_quiz_form(quiz): """Create quiz form with all its question choices, shuffle the choices for quiz page""" form = QuizForm() for i in range(10): form.questions[i].answers.choices = [ quiz.questions[i].correct_answer, quiz.questions[i].wrong_answer_1, quiz.questions[i].wrong_answer_2, quiz.questions[i].wrong_answer_3 ] random.shuffle(form.questions[i].answers.choices) form.questions[i].answers.label = quiz.questions[i].url return form
def quiz(): form = QuizForm() if current_user.answered is None: current_user.answered = dumps([]) db.session.commit() questions_to_display = Questions.query.filter( Questions.creatorid != str(current_user.id)).all() return render_template('quiz.html', questions_to_display=questions_to_display, form=form, users=getStandings()) else: alreadyAns = loads(current_user.answered) #Check the questions to display questions_to_display = Questions.query.filter( Questions.creatorid != str(current_user.id)).filter( ~Questions.questionid.in_(alreadyAns)).all() return render_template('quiz.html', questions_to_display=questions_to_display, form=form, users=getStandings())
def index(request): if request.method == 'POST': form = QuizForm(request.POST) if form.is_valid(): # TODO: Errors must be handled _id = form.cleaned_data["categories"] _category = Category.objects.get( id=_id) # TODO: cleaned data must be used number_of_questions = 6 _questions = _category.get_random_questions(number_of_questions) if len(_questions) == 0: form = QuizForm(request.POST) context_data = { 'form': form, 'error_message': "سوالی در این موضوع وجود ندارد" } return render(request, "quiz_index.html", context_data) print "random questions:" print _questions quiz = Quiz(category=_category) user1 = User.objects.get(username=request.user) quiz.set_user1(user1) user2 = User.objects.order_by('?').first() while user2 == user1: user2 = User.objects.order_by('?').first() quiz.set_user2(user2) quiz.save() quiz.questions = _questions quiz.save() print quiz.questions.all() #for question in _questions: # print "question to be added: " # print question.question # quiz.add_question(question) #quiz.save() # print "quiz questions:" + str(quiz.questions) # print "quiz id: " + str(quiz.id) print user2.email email = EmailMessage('new Challenge', 'quizdown.ir/quiz/start?quiz_id=' + ` quiz.id `, to=[user2.email]) email.send() request.session['_quiz_id'] = json.dumps(quiz.id) request.session['question_index'] = 0 request.session.save() request.session.modified = True return redirect('/quiz/start/') # start(None, quiz.id) # if a GET (or any other method) we'll create a blank form else: form = QuizForm(request.POST) context_data = {'form': form} return render(request, "quiz_index.html", context_data)
def test_quiz_form_valid(self): """Testing whether the quiz form is valid.""" form_data = {'name': 'Database', 'subject': 'CS306', 'difficulty': 1} form = QuizForm(data=form_data) self.assertTrue(form.is_valid())
def test_quiz_form_invalid(self): """Testing whether the quiz form is invalid.""" form2_data = {'name': 'Database', 'subject': 'CS306', 'difficulty': 5} form2 = QuizForm(data=form2_data) self.assertFalse(form2.is_valid())