我正在处理两个链接表单字段(
Class
和
Students
)用户从下拉菜单中选择一个类,然后“学生”窗体字段将使用相应的学生列表进行更新。
我使用的都是ajax逻辑,除了……除了……我在尝试应用
selected
属于
<option>
标签。
视图.py
def load_students(request):
classid = request.GET.get('classid')
contractid = request.GET.get('contractid')
# Lookup students for given class
students = Student.objects.getclass(classid=classid)
if(contractid):
# Generate list of students associated with this contract
contract_party_list = []
contract_parties = ContractParty.objects.get_contract_parties(
contractid=contractid
)
for mycontractparty in contract_parties:
contract_party_list.append(mycontractparty.partyuserid)
# Generate new student list (with appended contract user info)
student_list = []
for mystudent in students:
# Set flag to determine whether student is part of contract
if(mystudent.studentuserid in contract_party_list):
selectedFlag = True
else:
selectedFlag = False
# Add updated student info to new student list
student_list.append(
{
'studentuserid':mystudent.studentuserid,
'firstname':mystudent.firstname,
'lastname':mystudent.lastname,
'selectedFlag': selectedFlag
}
)
students = student_list
return render(request, 'dropdown_ajax.html', {'students': students})
下拉菜单ajax.html
{% if students %}
{% for student in students %}
<option
value="{{ student.studentuserid }}"
{% if student.selectedFlag %} selected="selected"{% endif %}
>
{{ student.firstname }} {{ student.lastname }}
</option>
{% endfor %}
{% endif %}
这条线给我带来了麻烦:
{% if student.selectedFlag %} selected="selected"{% endif %}
奇怪的行为是“selected”属性永远不会被应用,即使
student.selectedFlag
计算结果为true。
我试过几件事:
-
我把上面的线移到标签外面,看它能做什么。它显示正确条目的文本“selected”。
-
我换了
if student.selectedFlag
具有
if student.studentuserid == 1
而正确的学生是在这个领域被选中的。
-
我为
selectedFlag
而不是布尔值。我试过了
if student.selectedFlag == "True"
是的。没有什么。
我不知道是什么导致了这种行为。我猜这与django布尔变量在
<选项>
领域。