python - Django 1.6 : How to pass value from a dropdown to another template page

标签 python html django

我想获取用户选择的下拉字段的值,并在下一页使用它来根据下拉选择过滤一些个人资料列表。

我在我的 index.html 页面中有这个,并希望用户在下拉列表中选择一个选项,然后点击提交并重定向到 doclistings.html 页面

  <div class="form-group">
        <form action="/doclistings/" method="post">
        <select class="form-control" id="select">
          <option><b>Choose a Speciality...</b></option>
          <option value ="Dermatologist">Dermatologist</option>
          <option value = "Dentist">Dentist</option>
          <option value = "ENT">Ear, Nose and Throat (ENT)</option>
          <option value = "Opthalmologist">Eye Doctor</option>
          <option value = "Psychiatrist">Psychiatrist</option>
          <option value = "Orthopedist">Orthopedist</option>
        </select>
        <span class="input-group-btn">
          <button class="btn btn-primary" type="submit"  name="submit" id="ss-submit">Find Doctors</button>
        </span>
      </div>

文档列表.html

{% for doc in doclist %}
            {% if doc.specialization == } # value from the last page
            <div class = "doctorrow">
            <h2><a href="/docprofile/{{doc.id}}/">{{doc.name}}</a></h2>
            <h3> {{doc.specialization}}</h3>           
            </div>
            </div>
       {% endfor %}

View .py

def index(request):

if request.method == "POST":
    form = DropdownSelectionForm(request.POST)

    if form.is_valid():
        selection = form.cleaned_data['value']

        return HttpResponseRedirect('/doclistings')
else:
    form = DropdownSelectionForm()

return render(request, 'meddy1/index.html')

@csrf_exempt
def doclistings(request):
    return render(request, 'meddy1/doclistings.html', {'doclist': Doctor.objects.all()})

表单.py

class DropdownSelectionForm(forms.Form): 
    selection = forms.CharField()

最佳答案

尝试 POST,然后使用来自 request 的发布值在下一个 View 中呈现它。这是文档 -

https://docs.djangoproject.com/en/1.6/topics/forms/#using-a-form-in-a-view

编辑 您可以执行以下任一操作 -

  1. 将alldocs View 设置为表单中的form action并将form method设置为GET。因此,当发布表单时,您可以在 alldocs View 的 query string 中获取值。

  2. 使用索引 View 并通过检查 request.method 来检查是否执行了 POST 操作,然后从那里获取值并使用 redirect(来自 django.shortcuts ) 使用您需要的值作为参数重定向到您的 View 。

我之前提到的文档中记录了检查 POST 或 GET 的方式。

关于python - Django 1.6 : How to pass value from a dropdown to another template page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24135975/

相关文章:

Python 使用键从文本中提取值

python - 使用python3实现FFT和IFFT

html - 从右向左移动图像 - 动画不起作用

python - 找不到 'login'的反向按钮。 'login'不是有效的 View 函数或模式名称

django - 翻译 django 模板中的动态内容

python - 重命名 Django 模型中的默认 id 列

javascript - Django 如何配置为管理员使用备用静态目录

python - Django 中的 "Master page"管理

html - 使用 Skrollr 的窗帘滚动效果

javascript - 用于创建文本字段的下拉菜单