Pagination in django - original query string is lost

I use the code from the documentation to break the data:

try: data = paginator.page(request.GET.get('page')) except PageNotAnInteger: page = 1 data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) 

And the page:

 <div class="pagination"> <span class="step-links"> {% if data.has_previous %} <a href="?page={{ data.previous_page_number }}">previous</a> {% endif %} <span class="current"> <b>Page</b> {{ data.number }} of {{ data.paginator.num_pages }} </span> {% if data.has_next %} <a href="?page={{ data.next_page_number }}">next</a> {% endif %} </span> </div> 

But there is an error: when the url contains the query string and one click on the Pager, the original query string is lost. For instance:

 example.com?var1=33&var2=44 

and then when you click "page2", the URL becomes

 example.com?page=2 # var1=33&var2=44 is lost 

instead:

 example.com?var1=33&var2=44&page=2 

I did not find a standard or easy way to fix it. How can i do this?

UPDATE:

Of course, the names of the parameters, their values ​​and whether they exist or not are unknown.

+8
source share
3 answers

You can access the 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 directly access the parameters in your template. In your case, you will need to filter the page parameter. You can do something like this:

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

Another possible solution would be to create a list of parameters in your view. Pros: You can use clean and expressive methods on QueryDict .

It will look like this:

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

What is it! Now you can use the context variable in the template:

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

Look, the code looks clean and beautiful.

note: assumes your context contained in the context dict and your paginator in the paginator variable

+6
source

An easy way would be to include these variables in your template:

 <a href="?var1={{var1}}&var2={{var2}}&page={{ data.next_page_number }}">next</a> 

Just add var1 and var2 to context .

This is if the query string variables came from your backend. If they come from external / external, you can use something like How can I get query string values ​​in JavaScript? in your template and either edit the vars template directly or transfer the values ​​to your server.

0
source

Source: https://habr.com/ru/post/988237/


All Articles