2017-02-08 64 views
0

如何獲取由Django中的表單提交的所有選項,這是我使用的表單。如何獲取表單提交的所有選項

{% extends 'quiz/base.html' %} 
{% block content%} 
<h1>You are at quiz page</h1> 

<form action="{% url 'quiz:process_data' %}" method="post"> 
    {% csrf_token %} 
    {% for question in question_set %} 
     <h3>{{question.id}}.{{question.question_text }}</h3> 
     {% for option in question.options_set.all %} 
      <input type="radio" name="choice{{question.id}}" value="{{ option.options}}" > {{option.options}}<br> 
     {% endfor %} 
    {% endfor %} 
    <input type="Submit" name="Submit"> 
</form> 
{% endblock%} 

我試過selected_choice=request.POST,但得到這個作爲輸出csrfmiddlewaretokenchoice1Submitchoice3。我該如何解決這個問題?謝謝

+1

Request.POST是一本字典。所以只是'request.POST.get('form_field_name')' –

+0

請張貼您的form.py. –

回答

2

在django request.POST是類似字典的對象,詳見here。 因此獲得的參數選擇在視圖中,可以使用下面的語法:

selected_choice=request.POST.get('choice') 

這情況下返回choice值或None這是空的。

由於request.POST是類似字典的對象,你可以使用items()方法獲取所有值和它們進行過濾:

for k, v in request.POST.items(): 
    if k.startswith('choice'): 
     print(k, v) 

這將只打印在名稱choice文本的PARAMS。

0
selected_choice=request.POST.get('choice') 

上面應該工作得很好,但如果你是瘋了,你可以試試這個:

{% extends 'quiz/base.html' %} 
{% block content%} 
<h1>You are at quiz page</h1> 

<form action="{% url 'quiz:process_data' %}" method="post" id= "crazyform"> 
    {% csrf_token %} 
    {% for question in question_set %} 
     <h3>{{question.id}}.{{question.question_text }}</h3> 
     {% for option in question.options_set.all %} 
      <input type="radio" name="choice" value="{{ option.options}}" > {{option.options}}<br> 
     {% endfor %} 
    {% endfor %} 
    <input type="hidden" name="crazychoice" class="crazy" value="nothing"> 
    <input type="Submit" name="Submit"> 
</form> 
{% endblock%} 

那麼一些JQuery的:

$('#crazyform input').on('change', function() { 
$(".crazy").val($('input[name=choice]:checked', '#crazyform').val())}) 

每當你點擊一個單選按鈕,隱藏輸入字段的值將更改爲所選單選按鈕的值。

然後在您的視圖,您可以:

selected_choice = request.POST.get("crazychoice", "") 
相關問題