Example #1
0
def check(request, q_id, questionpaper_id=None):
    """Checks the answers of the user for particular question"""

    user = request.user
    q_paper = QuestionPaper.objects.get(id=questionpaper_id)
    paper = AnswerPaper.objects.get(user=request.user, question_paper=q_paper)
    if not user.is_authenticated() or paper.end_time < datetime.datetime.now():
        return my_redirect('/exam/login/')
    question = get_object_or_404(Question, pk=q_id)
    snippet_code = request.POST.get('snippet')
    skip = request.POST.get('skip', None)
    success_msg = False
    success = True
    if skip is not None:
        next_q = paper.skip()
        return show_question(request, next_q, questionpaper_id)

    # Add the answer submitted, regardless of it being correct or not.
    if question.type == 'mcq':
        user_answer = request.POST.get('answer')
    elif question.type == 'mcc':
        user_answer = request.POST.getlist('answer')
    else:
        user_code = request.POST.get('answer')
        user_answer = snippet_code + "\n" + user_code

    new_answer = Answer(question=question, answer=user_answer,
                        correct=False)
    new_answer.save()
    paper.answers.add(new_answer)

    # If we were not skipped, we were asked to check.  For any non-mcq
    # questions, we obtain the results via XML-RPC with the code executed
    # safely in a separate process (the code_server.py) running as nobody.
    correct, success, err_msg = validate_answer(user, user_answer, question)
    if correct:
        new_answer.correct = correct
        new_answer.marks = question.points
        new_answer.error = err_msg
        success_msg = True
    else:
        new_answer.error = err_msg
    new_answer.save()

    time_left = paper.time_left()
    if not success:  # Should only happen for non-mcq questions.
        if time_left == 0:
            reason = 'Your time is up!'
            return complete(request, reason, questionpaper_id)
        if not paper.question_paper.quiz.active:
            reason = 'The quiz has been deactivated!'
            return complete(request, reason, questionpaper_id)
        context = {'question': question, 'error_message': err_msg,
                   'paper': paper, 'last_attempt': user_code,
                   'quiz_name': paper.question_paper.quiz.description,
                   'time_left': time_left}
        ci = RequestContext(request)

        return my_render_to_response('exam/question.html', context,
                                     context_instance=ci)
    else:
        if time_left <= 0:
            reason = 'Your time is up!'
            return complete(request, reason, questionpaper_id)
        else:
            next_q = paper.completed_question(question.id)
            return show_question(request, next_q,
                                 questionpaper_id, success_msg)