我有一个选择。在项目更改时我重新加载页面,但重新加载后我选择了一个空白项目。如何记住所选项目?
teacher.html
<form id="form" method="POST">{% csrf_token %}
<select name="choose_teacher" onChange="this.form.submit();" blank_choice='Please choose:' >
<option value="{{ 0 }}">blank</option>
{% for item in query_results %}
<option value="{{ item.id }}">{{ item.title}} {{ item.name }} {{ item.surname }}</option>
{% endfor %}
</select>
</form>
{{ teacher_id }}
views.py
def teacher(request):
if request.method == 'POST':
if 'choose_teacher' in request.POST:
teacher_id = request.POST['choose_teacher']
query_results = Teacher.objects.all()
context = {'teacher_id': teacher_id,
'query_results': query_results}
return render(request, 'planner/teacher.html', context)
else:
query_results = Teacher.objects.all()
context = {'query_results': query_results}
return render(request, 'planner/teacher.html', context)
:编辑:
<form id="form" method="POST">{% csrf_token %}
<select name="choose_teacher" onChange="this.form.submit();">
{% for item in query_results %}
<option value="{{ item.id }}"
{% ifequal teacher_id item.id %}selected{% endifequal %}>{{ item.title }} {{ item.name }} {{ item.surname }}</option>
{% endfor %}
</select>
</form>
答案 0 :(得分:2)
将您的模板select
选项更改为:
<option value="{{ item.id }}"
{% ifequal teacher_id item.id %}selected{% endifequal %}
>{{ item.title}} {{ item.name }} {{ item.surname }}</option>
它将测试选项ID是否等于teacher_id
,如果为true,则添加selected
标记。
与选项0相同:
<option value="0" {% ifequal teacher_id 0 %}selected{% endifequal %}>blank</option>