我试图实现一个下拉表单,根据下拉列表中的选择过滤对象。我没有遇到任何问题,但是当没有选择任何内容并点击提交时,它会给我一个错误。我希望它不过滤任何东西,只是给出整个对象列表,但我在线上得到以下错误Specialization matching query does not exist
spec = Specialization.objects.get(name = s_name)
以下是我的表单
的模板<form action="/doclistings/" method="GET" >
<select class="form-control" id="selection" name="selection">
<option><b>Choose a Speciality...</b></option>
{% for value, text in form.selection.field.choices %}
<option name="choicemade" value="{{ value }}">{{ text }}</option>
{% endfor %}
<!-- {% csrf_token %} -->
</select>
<span class="input-group-btn">
<button class="btn btn-primary" type="submit" name="submit" id="ss-submit">Find Doctors</button>
</span>
</form>
这是表格
MY_CHOICES = (
('Dermatologist', 'Dermatologist'),
('Dentist', 'Dentist'),
('Orthopedist', 'Orthopedist'),
('Pediatrician', 'Pediatrician'),
)
class DropdownSelectionForm(forms.Form):
selection = forms.ChoiceField(choices=MY_CHOICES, widget = forms.Select, required = False)
genderselect = forms.ChoiceField(choices=GENDER_CHOICES, widget= forms.Select, required = False)
这是呈现下拉表单
的视图def index(request):
d = getVariables(request,dictionary={'page_name': "Home"})
if request.method == "POST":
form = DropdownSelectionForm(request.POST)
if form.is_valid():
selection = form.cleaned_data['selection']
return HttpResponseRedirect('/doclistings')
else:
form = DropdownSelectionForm()
return render(request, 'meddy1/index.html', {'form': form})
以下是根据选择
渲染对象的视图def doclistings(request):
d = getVariables(request)
if request.method == "GET":
s_name = request.GET['selection']
if s_name == "":
doctors = Doctor.objects.all().order_by('-netlikes')
else:
spec = Specialization.objects.get(name = s_name)
doctors = Doctor.objects.filter(specialization = spec).order_by('-netlikes')
else:
return HttpResponseRedirect('/doclistings')
d['doctors'] = doctors
return render_to_response('meddy1/doclistings.html',d)
答案 0 :(得分:1)
这就是你应该使用QueryDict方法的原因:
s_name = request.GET.get('selection', None)
if not s_name:
#if s_name is None
#...
这样,如果s_name不存在,它将正确回退。