我在同一个html页面中为每一行提供了多种表单(选择选择表单)。假设选项为EDIT
,UPDATE
,ADD
,如果有5行,并且用户为其中两行选择UPDATE
,则点击Submit
,我的观点将处理请求。
要处理此请求,我需要一个选定列表:
[{'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>
答案 0 :(得分:1)
您的数据字段位于表单标记的旁边,这就是您从POST
获取任何内容的原因。将您的数据字段放在表单标记中:
<form action='' method="POST"><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='41f4aa9cc46e3e21bb46c99bc992973a' /></div>
<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>