20

我应该使用下一个构造吗?

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>

我怎么解决这个问题?我需要写什么?

4

3 回答 3

21

给标签起个名字,比如

<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'] 
于 2012-07-20T20:14:41.400 回答
12

我建议通过邮寄方式发送您的数据:

<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

于 2012-07-20T20:55:45.090 回答
2

在“your_app_folder”中创建一个文件 forms.py

在forms.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')
于 2016-09-08T02:24:21.677 回答