1
我在同一個html頁面中爲每一行提供了幾種表單(select choice form)。假設選項爲EDIT
,UPDATE
,ADD
,如果有5行,並且用戶爲兩行選擇了UPDATE
,然後單擊Submit
,我的視圖將處理該請求。如何在Django的POST後從多個表單中獲取值?
處理此請求,我需要選擇的選項列表:
[{'row1':'UPDATE', 'row2': 'UPDATE'}] (okay... I need to be able to distinguish which choice belongs to which row...)
讓我們說這是我的html文件。
<table>
<tr>
<td>{{ form.as_p}}</td>
<td> 121 </td>
</tr>
<td>{{ form.as_p}}</td>
<td> 212 </td>
</table>
<form action='' method="POST">{% csrf_token %}
<input type="submit" name="Submit!"></input>
</form>
當它呈現,我們有這個
<td><p><label for="id_choice_field">Choice field:</label> <select name="choice_field" id="id_choice_field">
<option value="value1">First</option>
<option value="value2">Second</option>
</select></p></td>
<td> 212 </td>
</table>
<form action='' method="POST"><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='41f4aa9cc46e3e21bb46c99bc992973a' /></div>
<input type="submit" name="Submit!"></input>
</form>
我試圖
e = request.POST.getlist('choice_field')
return HttpResponse(e)
它給了我一個空白頁,所以沒有什麼.....
我如何從整個表中獲取選定值的列表(以及它的相關數據,如第#行)?
謝謝。
最終代碼
views.py
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from forms import MyForm
from django.core.context_processors import csrf
def my_form(request):
if request.method == "POST":
form = MyForm(request.POST)
e = request.POST.getlist("choice_field")
return HttpResponse(e)
else:
form = MyForm()
c = {'form':form}
c.update(csrf(request))
return render_to_response('hello.html', c)
forms.py
from django import forms
CHOICES = (('value1', 'First',),('value2', 'Second',))
class MyForm(forms.Form):
choice_field = forms.ChoiceField(choices=CHOICES)
hello.html的
<form action='' method="POST">{% csrf_token %}
<table>
<tr>
<td>{{ form.as_p}}</td>
<td> 121 </td>
</tr>
<td>{{ form.as_p}}</td>
<td> 212 </td>
</table>
<input type="submit" name="submit"></input>
</form>
是的。你是對的!謝謝!微妙的錯誤是如此昂貴! – User007 2012-03-07 03:29:51