我想获取用户选择的下拉字段的值,并在下一页使用它来根据下拉选择过滤一些个人资料列表。
我在我的 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
编辑 您可以执行以下任一操作 -
将alldocs View 设置为表单中的
form action
并将form method
设置为GET
。因此,当发布表单时,您可以在 alldocs View 的query string
中获取值。使用索引 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/