2

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" 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 %}

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.

Alexei
  • 95
  • 1
  • 2
  • 5
  • 4
    If you solved the problem, you should post that as an answer and accept it. – Ismail Badawi Jun 27 '11 at 23:38
  • I'd refer to this answer http://stackoverflow.com/questions/1116019/submitting-a-get-form-with-query-string-params-and-hidden-params-disappear/1116026#1116026 Which would suggest that adding the queryString parameters as hidden fields is the best idea. and I also concur with isbadwi, please post a nice answer for others to read. – James Khoury Jun 28 '11 at 01:31

1 Answers1

0

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>