我应该使用下一个结构吗?
def PageObjects(request):
q = bla_bla_bla(bla_bla)
answer = request.POST['value']
<form action="PageObjects" method="get">
<select >
<option selected="selected" disabled>Objects on page:</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
<input type="submit" value="Select">
</form>
我该如何解决这个问题?我需要写什么?
答案 0 :(得分:11)
为标记命名,例如
<select name="dropdown">
<option selected="selected" disabled>Objects on page:</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
在视图中访问它,如
def PageObjects(request):
q = bla_bla_bla(bla_bla)
answer = request.GET['dropdown']
答案 1 :(得分:3)
我建议您发送数据:
<form action="PageObjects" method="post">
<select >
<option selected="selected" disabled>Objects on page:</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
<input type="submit" value="Select">
</form>
您应该通过cleaned_data
词典访问您的表单值:
def page_objects(request):
if request.method == 'POST':
form = YourForm(request.POST)
if form.is_valid():
answer = form.cleaned_data['value']
我真的建议您阅读Django文档:
https://docs.djangoproject.com/en/1.4/topics/forms/#using-a-form-in-a-view
答案 2 :(得分:1)
在'your_app_folder'
中创建一个文件forms.py form.py中的:
class FilterForm(forms.Form):
FILTER_CHOICES = (
('time', 'Time'),
('timesince', 'Time Since'),
('timeuntil', 'Time Untill'),
)
filter_by = forms.ChoiceField(choices = FILTER_CHOICES)
在views.py中
from .forms import FilterForm
def name_of_the_page(request):
form = FilterForm(request.POST or None)
answer = ''
if form.is_valid():
answer = form.cleaned_data.get('filter_by')
// notice `filter_by` matches the name of the variable we designated
// in forms.py
此表单将生成以下html:
<tr><th><label for="id_filter_by">Filter by:</label></th><td><select id="id_filter_by" name="filter_by" required>
<option value="time" selected="selected">Time</option>
<option value="timesince">Time Since</option>
<option value="timeuntil">Time Untill</option>
</select></td></tr>
注意选择属性的选项字段,当您提交表单时,在views.py文件中,您将从selected
属性中获取数据
answer = form.cleaned_data.get('filter_by')