Django在提交时保留查询字符串

Django在提交时保留查询字符串,django,forms,Django,Forms,我有一个基于管理员搜索表单模板的搜索表单: {% 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">

我有一个基于管理员搜索表单模板的搜索表单:

{% 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 %}
{%load adminmedia%}
{%load i18n%}
{%if cl.search_fields%}
{%if show_result_count%}
{%blocktrans count cl.search_find_num as counter%}{{{counter}}结果{%复数%}{{counter}}结果{%endblocktrans%}()
{%endif%}
{cl.params.items%中的对的%s}
{%ifnotequal对。0搜索\u var%}{%endifnotequal%}
{%endfor%}
document.getElementById(“搜索栏”).focus();
{%endif%}
提交搜索时,搜索文本会正确地传递到查询字符串,但不幸的是,它会删除可能存在的任何其他内容。例如,如果我的URL为
www.example.com/?a=whatever&b=something
,则在提交搜索后,它将变成
www.example.com/?q=searchtext
,而不是
www.example.com/?a=whatever&b=something&q=searchtext
。我很确定这个问题与表单的“action”属性有关,但我对HTML不够精通,无法准确地指出它应该是什么

编辑:问题解决了,我刚刚在HTML表单中添加了隐藏字段,保留了我想要保留的值。

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>

搜寻

如果你解决了这个问题,你应该把它作为一个答案发布并接受它。我会参考这个答案,它建议将queryString参数添加为隐藏字段是最好的主意。我也同意isbadwi的观点,请发布一个好的答案供其他人阅读。