2016-03-02 101 views
0

我正在创建一个页面,其中显示带选项的多选题作为单选按钮(并且应该根据用户选择的选项向用户提交结果)。我使用下面的模型问题:Django-通过模板传递过程数据

class Question(models.Model): 
    q_id = models.IntegerField(primary_key=True) 
    q_text = models.TextField(blank=True, null=True) 
    choice1 = models.TextField(blank=True, null=True) 
    choice2 = models.TextField(blank=True, null=True) 
    choice3 = models.TextField(blank=True, null=True) 
    choice4 = models.TextField(blank=True, null=True) 
    correct_ans = models.TextField(blank=True, null=True) 

其中显示的问题是视图:

def index(request): 
    latest_question_list = Question.objects.order_by('q_id')[:10] 
    return render(request,'index.html',{'latest_question_list': latest_question_list}) 

和模板(的index.html)是:

<body> 
    {% if latest_question_list %} 
    <form action="/result/" method="post"> 
     <ul> 
     {% for question in latest_question_list %} 

      <li>{{ question.q_text }}</li> 
      <input type="radio" name="{{question.q_id}}" value="1" />{{ question.choice1}}<br> 
      <input type="radio" name="{{question.q_id}}" value="2" />{{ question.choice2}}<br> 
      <input type="radio" name="{{question.q_id}}" value="3" />{{ question.choice3}}<br> 
      <input type="radio" name="{{question.q_id}}" value="4" />{{ question.choice4}}<br> 

     {% endfor %} 
     </ul> 
     <input style="margin-left:2%" type="submit" value="Submit"/> 
    </form> 
    {% endif %} 
</body> 

我想知道我应该在“结果”视图中写什么。 也就是说,我如何检查用户选择的选项,并将其与问题模型中存储的正确的问题选项对进行匹配,以便在“结果”页面中显示用户的分数。

回答

1

你确实有问题的数量,所以在你的结果来看,申报字典和重复这样的, dict = {} for i in numberOfQuestion: dict[i] = request.POST.get('questions.'+i) #dict will have all answers with question numbers

1

设置您urls.py

def yourView(request): 
    q = request.GET.get('q') 
    # note that 'q' is the value of the input 
    # the logic goes here 

因此改变你的输入 - ><input type="radio" name="q" value="1" />{{ question.choice1}}<br>

+0

但我希望'name'属性是唯一的,否则我将能够从latest_question_list中的所有问题中仅选择一个问题的选择。如果我通过名称中的q_id,我怎样才能将它恢复到视图中? – deveshasha