Python Django 1.6:表单中未绑定的LocalError
我得到一个未绑定的本地错误 赋值前引用的局部变量“genderselect” 在线131 in view.pyPython Django 1.6:表单中未绑定的LocalError,python,django,forms,views,Python,Django,Forms,Views,我得到一个未绑定的本地错误 赋值前引用的局部变量“genderselect” 在线131 in view.py gend = Doctor.objects.get(gender = genderselect) 我在两个不同的模板中有相同的表单 Index.html <div class="signup"> <div class="form-group"> <form action="" method="post" >
gend = Doctor.objects.get(gender = genderselect)
我在两个不同的模板中有相同的表单
Index.html
<div class="signup">
<div class="form-group">
<form action="" method="post" >
<select class="form-control" id="selection" name="selection">
<option><b>Find a Doctor...</b></option>
{% for value, text in form.selection.field.choices %}
<option 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>
</div>
</div>
我猜我的表格没有验证。我不知道为什么会这样
这是我正在使用的表单
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)
当
request.method==“GET”
时,未设置变量genderselect
。它仅在提交表单时设置,此时request.method==“POST”
您可能需要重新构造代码,以便为GET
请求适当地设置该变量。行
gend = Doctor.objects.get(gender = genderselect)
使用变量genderselect
,该变量仅在请求方法为POST时存在。也就是说,当加载页面时,通常会在赋值之前引用局部变量“genderselect”
——因为您使用的是未声明的变量(python识别代码的其他部分定义了genderselect
,并假设您在赋值之前使用它,因此会出现错误)
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)
gend = Doctor.objects.get(gender = genderselect)