提交后如何保留所选的选项?

时间:2018-11-22 15:11:27

标签: html django

是否有办法保留使用for循环的下拉列表中的选定选项?

views.py:

...

queryC = request.GET.get('clientList', '')
queryT = request.GET.get('topicList', '')
topicList = Topic.objects.all().order_by('Name')
clientList = ClientDetail.objects.all().order_by('Client_name')

...

return render(request, 'app/search_es20.html', {
    "responses": responses,
    "query": q,
    "queryR": queryR,
    "noOfResults": resultsCount,
    "username": username,
    "topicList": topicList,
    "clientList": clientList,
    "queryC": queryC,
    "queryT": queryT,
})

html:

Topic
   <select name="topicList">
       <option value="empty"></option>
       {% for element in topicList %}
       <option value={{element.Name}}>{{ element.Name }}</option>
       {% endfor %}
   </select>

Client
   <select name="clientList">
       <option value="empty"></option>
       {% for element in clientList %}
       <option value={{element.Client_name}}>{{ element.Client_name }}</option>
       {% endfor %}
   </select>

我尝试使用IF语句,但是操作不正确

1 个答案:

答案 0 :(得分:1)

如果您可以根据上下文(或根据要求)访问所选值,则可以执行以下操作:

<option value={{element.Client_name}} {% if element.Client_name == some_var %} selected {% endif %}>{{ element.Client_name }}</option>