【发布时间】:2014-08-11 15:13:26
【问题描述】:
我收到这个 unboundLocal 错误,上面写着 赋值前引用的局部变量“genderselect”
在 view.py 的第 131 行
gend = Doctor.objects.get(gender = genderselect)
我在两个不同的模板中有相同的表单
索引.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>
doclisting.html
<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 %}
</select>
<select class="form-control" id="genderdropdown" name="genderdropdown">
<option><b>Select a Gender</b></option>
{% for value, text in form.genderselect.field.choices %}
<option value="{{ value }}">{{ text }}</option>
{% endfor %}
</select>
<span class="input-group-btn">
<button class="btn btn-primary" type="submit" name="submit" id="ss-submit">Search</button>
</span>
</div>
{% csrf_token %}
</form>
这是我收到错误的视图
def doclistings(request):
d = getVariables(request)
if request.method == "POST":
form = DropdownSelectionForm(request.POST)
print form.errors
if form.is_valid():
selection = form.cleaned_data['selection']
genderselect = form.cleaned_data['genderselect']
d['usergendselect'] = genderselect
request.session["selection"] = request.POST['selection']
return HttpResponseRedirect('/doclistings')
else:
form = DropdownSelectionForm()
s_name = request.session.get('selection') # Change variable name
d['userselection'] = s_name # Update this for new variable name
gend = Doctor.objects.get(gender = genderselect)
spec = Specialization.objects.get(name=s_name) # Get spec object
doctors = Doctor.objects.filter(specialization = spec, gender = gend).order_by('-likes')
d['doctors'] = doctors
d.update({'form': form})
return render_to_response('meddy1/doclistings.html',d)
我猜我的表单没有通过验证。我不知道为什么会这样。
这是我正在使用的表格
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)
【问题讨论】: