Django Pagination & Filters appending to url rather than replacing

I’ve been using a templatetag solution I found on here a while ago, could’ve referenced it, but I’ll just post the snippet:

  1. Create a templatetag, if you dont know know how. Read here. It’s quite easy and not that long a task.

  2. Add the following code in your filters/tags file:

@register.simple_tag(takes_context=True)
def param_replace(context, **kwargs):
    d =context['request'].GET.copy()
    for k,v in kwargs.items():
        d[k] = v
    for k in [k for k,v in d.items() if not v]:
        del d[k]
    return d.urlencode()

Load your custom filters in your template {% load "file_name_here" ... %}

Then on your pagination links:

<a class="page-link" href="?{% param_replace page=current_page.next_page_number %}"> Next </a>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top