[英]Strange behavior in select drop-down in a Django template
我正在研究两个链接的表单字段(“ Class
和“ Students
),其中用户从下拉菜单中选择一个班级,然后“学生表单”字段会使用相应的学生列表进行更新。
我已经全部使用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布尔变量有关。
我不认为这是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 %}
像往常一样...该解决方案在休息后表现出来:)这是官方的...我是个白痴。 在测试中,我正在研究两种不同的情况。 这给了我“怪异的行为”,我没有传递contractid
价值。 因此,它永远不会涉及设置selected
选项的逻辑。 天哪! 感谢您的提示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.