python - Django select how to remember choosen value? -
i have select. on item change reload page, after reloading have blank item choosen. how make remember choosen item?
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> {% 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)
:edit:
<form id="form" method="post">{% csrf_token %} <select name="choose_teacher" onchange="this.form.submit();"> {% 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>
change template select
options to:
<option value="{{ item.id }}" {% ifequal teacher_id item.id %}selected{% endifequal %} >{{ item.title}} {{ item.name }} {{ item.surname }}</option>
it test if the option id equal teacher_id
, , add selected
tag if true.
the same option 0:
<option value="0" {% ifequal teacher_id 0 %}selected{% endifequal %}>blank</option>
Comments
Post a Comment