动态视图未显示

时间:2013-03-25 15:39:23

标签: django python-2.7 django-forms django-views

我正在尝试进行测验,如果您回答错误的问题,您会看到该问题会被添加到错误的问题列表中。

问题可用于多个quizes,因此我无法硬编码问问题_1然后问题_2等。

当我加载页面时,我会看到第一个问题但是如果我提交或刷新,我会看到right.html模板。它不会问所有问题。

在呈现right.html页面之前,它应该询问所有问题

for question in quiz.questions.all():
   if question not in asked_questions:
        asked_questions.append(question)
        return answer_question(request, quiz_id, question.id, module_list)

models.py

class Choice(models.Model):
    choice = models.CharField(max_length=64)
    def __unicode__(self):
        return self.choice

#create a multiple choice quiz to start
class Question(models.Model):
    question = models.CharField(max_length=64)
    answer = models.CharField(max_length=64)
    choices = models.ManyToManyField(Choice)
    module = models.CharField(max_length=64)

    def __unicode__(self):
        return self.question

class Quiz(models.Model):
    name = models.CharField(max_length=64)
    questions = models.ManyToManyField(Question)

    def __unicode__(self):
        return self.name

views.py

asked_questions = []
module_list = []
module_list.append('test')

def take_quiz(request, quiz_id):
    quiz = Quiz.objects.get(id=str(quiz_id))

    for question in quiz.questions.all():
        if question not in asked_questions:
            asked_questions.append(question)
            return answer_question(request, quiz_id, question.id, module_list)
    #quiz is over
    return render (request, 'right.html')

def answer_question(request, quiz_id, question_id, module_list):
    question = Question.objects.get(id=question_id)
    #module_list = []
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        choices = [(i, i) for i in question.choices.all()]
        form.fields['selection'].choices = choices

        if form.is_valid():
            if form.cleaned_data['selection'] != str(question.answer):
                module_list.append(question.module)
            return take_quiz(request, quiz_id)
    else:
        form = QuestionForm()
        choices = [(i, i) for i in question.choices.all()]
        form.fields['selection'].choices = choices

    return render(request, 'answer_question.html', {'question':question, 'form':form, 'module_list':module_list})

2 个答案:

答案 0 :(得分:0)

如果你计划托管这个并在网上提供,你应该重新开始。您不应该使用这样的列表来存储内容,而应该使用sessionscache。此外,您最好使用FormWizard进行测验,因为它旨在完成您要执行的操作:处理多个表单并处理它们。

答案 1 :(得分:0)

也许你应该尝试

return HttpResponseRedirect(reverse('answer_question', args=[quiz_id, question_id, module_list]))

将视图重定向到另一个视图。

p.s。:reverse应包含'answer_question'视图的名称