我正在处理两个链接的表单字段(Class
和Students
),其中用户从下拉菜单中选择一个班级,然后Student表单字段会使用相应的学生列表进行更新
我已经全部使用AJAX逻辑了,除了...例外...在尝试将selected
属性应用于<option>
标签时遇到了一些奇怪的行为。
views.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})
dropdown_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 %}
奇怪的行为是,即使student.selectedFlag
的值为True,也永远不会应用“ selected”属性。
我尝试过的几件事:
我将行移到了标签之外,以查看它会做什么。它会为正确的条目显示文本“已选择”。
我将if student.selectedFlag
替换为if student.studentuserid == 1
,并在该字段中选择了正确的学生。
我为selectedFlag
传递了“ True” /“ False和数值”,而不是布尔值。我尝试了if student.selectedFlag == "True"
。什么都没有。
我不确定是什么原因导致了这种行为。我猜这与在<option>
字段中未正确评估Django布尔变量有关。
答案 0 :(得分:0)
我不认为这是django的问题-这是html的问题。 html属性应被视为布尔值(存在/不存在),而不是给定值“ selected”。正确呈现的html应该看起来像这样:
<option value="value" selected>...</option>
不是这个,我想这就是您的情况:
<option value="value" selected="selected">...</option>
所以更正后的代码如下:
dropdown_ajax.html
{% if students %}
{% for student in students %}
<option
value="{{ student.studentuserid }}"
{% if student.selectedFlag %} selected{% endif %}
>
{{ student.firstname }} {{ student.lastname }}
</option>
{% endfor %}
{% endif %}
答案 1 :(得分:0)
像往常一样...该解决方案在休息后表现出来:)这是官方的...我是个白痴。在测试中,我正在研究两种不同的情况。这给了我“怪异的行为”,我没有传递contractid
值。因此,它永远不会进入设置selected
选项的逻辑。天哪!感谢您的提示。