Pagination in django - the original query string gets lost

You can access parameters from your request directly in your template if you activate django.core.context_processors.request in your settings. See https://docs.djangoproject.com/en/1.7/ref/templates/api/#django-core-context-processors-request

Then you can access parameters in your template directly. In your case you'll need to filter page parameter. You could do something like this:

href="?page={{ data.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"

Another possible solution can be to construct parameters list in your view. Pros: you can use clean and expressive methods on QueryDict.

It will be look like this:

get_copy = request.GET.copy()
parameters = get_copy.pop('page', True) and get_copy.urlencode()
context['parameters'] = parameters

That's it! Now you can use your context variable in template:

 href="?page={{ paginator.next_page_number }}&{{ parameters }}" 

See, code looks clean and nicely.

note: assumes, that your context contained in context dict and your paginator in paginator variable

Tags:

Python

Django