我收到了这个unboundLocal错误 本地变量' genderselect'在分配前引用
在view.py
的第131行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>
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)
答案 0 :(得分:2)
request.method == 'GET'
未设置变量genderselect
时。它仅在提交表单时设置,当时为request.method == 'POST'
。
您可能希望重新构建代码,以便为GET
请求适当设置该变量。
答案 1 :(得分:0)
该行
gend = Doctor.objects.get(gender = genderselect)
使用变量genderselect
,该变量仅在请求方法为POST时才存在。这意味着,当正常加载页面时,您会得到local variable 'genderselect' referenced before assignment
- 因为您正在使用未声明的变量(python认识到代码的其他部分定义了genderselect
并假设您正在使用它在分配之前,因此错误)。