Search code examples
djangodjango-urlsget-request

Django URL parameters replace each other


Perhaps my question will seem somewhat simple and understandable, but even so.

In my project, I use standard pagination and sorting.

The problem is that they replace each other in the get request, for example I sort them and if I go to the second page then the set is not sorted. I understand the reason and it seems the answer lies on the top, but even so I could not find it.

Sorting:

<a href="?order_by=counter__service__name_service&sort={{ sort_type }}">Counter</a>

Pagination example:

<a class="page-link" href="?page={{ history_application.previous_page_number }}">&laquo;</a>

The question is how to save the parameters that were transmitted earlier.


Solution

  • Try using a Django templatetag that updates the current request.GET parameters and adds new parameters using urllib.urlencode.

    Create a templatetag:

    # templatetags.app_tags
    
    import urllib
    
    @register.simple_tag(takes_context=True)
    def url_add_query(context, **kwargs):
        """ Updates the current path from existing GET parameters. """
        request = context.get('request')
    
        get = request.GET.copy()
        get.update(kwargs)
        return u'{path}?{params}'.format(path=request.path,
                    params=urllib.urlencode(get, 'utf-8'))
    

    On your HTML template:

    {% load app_tags %}
    
    <a href="{% url_add_query page=history_application.previous_page_number %}">&laquo;</a>