我的搜索表单基于管理搜索表单模板:
{% load adminmedia %}
{% load i18n %}
{% if cl.search_fields %}
<div id="toolbar"><form id="changelist-search" action="." method="get">
<div><!-- DIV needed for valid HTML -->
<label for="searchbar"><img src="{% admin_media_prefix %}img/admin/icon_searchbox.png" alt="Search" /></label>
<input type="text" size="40" name="{{ SEARCH_VAR }}" value="{{ search_string|escape }}" id="searchbar" />
<input type="submit" value="{% trans 'Search' %}" />
{% if show_result_count %}
<span class="small quiet">{% blocktrans count cl.search_found_num as counter %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktrans %} (<a href="?{% if cl.is_popup %}pop=1{% endif %}">{% blocktrans with cl.search_total_num as full_result_count %}{{ full_result_count }} total{% endblocktrans %}</a>)</span>
{% endif %}
{% for pair in cl.params.items %}
{% ifnotequal pair.0 search_var %}<input type="hidden" name="{{ pair.0 }}" value="{{ pair.1 }}"/>{% endifnotequal %}
{% endfor %}
</div>
</form></div>
<script type="text/javascript">document.getElementById("searchbar").focus();</script>
{% endif %}
提交搜索时,搜索文本会正确传递到查询字符串,但遗憾的是它会删除可能存在的任何其他内容。例如,如果我的网址为www.example.com/?a=whatever&b=something
,则在提交搜索后,它会变为www.example.com/?q=searchtext
,而不是www.example.com/?a=whatever&b=something&q=searchtext
。我很确定这个问题与表单的“action”属性有关,但我不熟悉HTML,以确切地指出它应该是什么。
编辑:问题解决了,我只是在HTML表单中添加了隐藏字段,保留了我想保留的值。
答案 0 :(得分:1)
view.py:
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(**kwargs)
context['search_word'] = self.search_word
return context
template.html:
<form class="d-flex" action="{% url 'polls:index' %}" method="get">
<input class="form-control me-2" type="search"
placeholder="Search" aria-label="Search"
name="search" value="{{ search_word }}">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>