开发者

Django keeping query string on submit

I have a search form that's based off of the admin search form template:

{% 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" valu开发者_JAVA百科e="{% 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 %}

When the search is submitted, the search text is passed correctly up to the query string, but unfortunately it gets rid of anything else that might have been there. For example, if I have a URL of www.example.com/?a=whatever&b=something, after the search is submitted it becomes www.example.com/?q=searchtext, as opposed to www.example.com/?a=whatever&b=something&q=searchtext. I'm pretty sure the problem has something to do with the "action" attribute of the form, but I'm not well enough versed in HTML to pinpoint exactly what it should be.

Edit: problem solved, I just added hidden fields to the HTML form that preserved the values I wanted to preserve.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜