Search code examples
pythondjangogetsearch-form

GET request the django way


I am playing with Django and have the following question.

I have a search form in some template:

<form role="search" method="get" action="{% url 'polls:search' %}">
....
<\form>

which, for example, forms the following request:

 http://127.0.0.1:8000/search/?text=dog&year=2017

The corresponding function in the view.py file works well with this request.

At some point in other template i need to make a link which leads to

http://127.0.0.1:8000/search/?text=&year=2017

I do the following:

 <a href="{% url 'polls:search' %}?text=&year=2017">

It looks a little bit ugly and maybe incorrect. Is there another way?

For example, is it possible to form the get request in the Django way:

http://127.0.0.1:8000/search/dog/2017

So in the other template, one can write

 <a href="{% url 'polls:search' %} text='' year=2017">

Solution

  • Semantically, search terms should rather be get parameters. You can write a simple template tag that takes keyword arguments and use a QueryDict to handle the proper url encoding:

    # some_installed_app/templatetags/my_tags.py
    from django.http import QueryDict
    from django import template
    
    register = template.Library()
    
    @register.simple_tag
    def querystring(**kwargs):
        d = QueryDict(mutable=True)
        d.update(kwargs)
        return d.urlencode()
    

    And in the template, you can do:

    # template.html
    {% load my_tags %}
    <a href="{% url 'polls:search' %}?{% querystring text='' year=2017 %}">
    # http://127.0.0.1:8000/search/?text=&year=2017
    

    It will be able to handle awkward data properly, e.g.:

    ...{% querystring text='foo bar' %}
    # ...text=foo+bar