示例#1
0
def do_quizchallenge( request, world, stage, challenge ):
    here = get_stage(world, stage)
    if not here.challenge:
        if here.tutorial: return redirect( "lesson", world = world, stage =stage )
        else: raise Http404()
    quizID = request.POST.get("quizID")
    challenge, answer_map = request.session.get(quizID)
    
    if challenge is None or answer_map is None: pass # raise shenanigans.
    
    # First we extract all of the responses from the form.
    responses = []
    q = 0
    while "q%d"%q in request.POST:
        responses.append( request.POST.getlist("q%d"%q) )
        q += 1
    
    # For each of the questions, we create a QuizAnswer and store it in the
    # answers list. Assuming we get all the way through without any shenanigans,
    # we'll save all of those models, then create a single QuizChallengeResponse
    # to hold them.
    answers = []
    score = 0
    total = 0
    for q in range(len(responses)):
        if q not in answer_map: pass # raise shenanigans.
        total += 1
        QA = QuizAnswer()
        raw_response_list = responses[q]
        QA.question, choice_map = answer_map[q]
        response_list = []
        for r in raw_response_list:
            if r in answer_map: response_list.append( answer_map[r] )
        if 'A' in response_list: QA.selectedA = True
        if 'B' in response_list: QA.selectedB = True
        if 'C' in response_list: QA.selectedC = True
        if 'D' in response_list: QA.selectedD = True
        if 'E' in response_list: QA.selectedE = True
        
        ans = True
        if QA.question.multiple_ok:
            if QA.selectedA != QA.question.correctA: ans = False
            if QA.selectedB != QA.question.correctB: ans = False
            if QA.selectedC != QA.question.correctC: ans = False
            if QA.selectedD != QA.question.correctD: ans = False
            if QA.selectedE != QA.question.correctE: ans = False
        else:
            ans = False
            if QA.selectedA == QA.question.correctA: ans = True
            if QA.selectedB == QA.question.correctB: ans = True
            if QA.selectedC == QA.question.correctC: ans = True
            if QA.selectedD == QA.question.correctD: ans = True
            if QA.selectedE == QA.question.correctE: ans = True
        if ans: score += 1
        QA.correct = ans
        
        answers.append(QA)
    
    # We made it through safely! Now we save the response in the DB.
    for QA in answers: QA.save()
    QCR = QuizChallengeResponse()
    QCR.quiz = challenge
    QCR.student = request.user.student
    QCR.score = score
    QCR.correct = (score == total)
    QCR.save()  # Can't do many-to-many until we save it once.
    for QA in answers: QCR.answers.add(QA)
    QCR.save()
    
    # If QCR was correct, add the stage to the Student's completion record.
    
    return HttpResponse( str(responses) )