Django - pagination in a template using multiple GET parameters

I am using Django Paginator, and I want to have several get options available, such as: page = 1 sort_by = price

However, in my template tags, I:

Showing items sorted by {{ SORT_PARAM }}. Showing {{ ITEMS_PER_PAGE }} items per page. {% if has_prev %} <a href="?page={{ prev_page }}">Previous</a> | {% endif %} 

However, this does not save other GET variables. I mean if I browse

 page/?page=1&sort_by=price 

and I click the link in the template snippet above, I will go to

 page=2 

instead

 page=2&sort_by=price 

I mean, href does not save other GET parameters.

One solution - I can enter all possible GET parameters in href, for example

 <a href="?page={{ prev_page }}&items_per_page={{ ITEMS_PER_PAGE }}&sort_param={{ SORT_PARAM }}">Previous</a> 

but it will become less scalable, the more arguments I want to add to my view. I suppose there should be an automatic way to get all the GET parameters and then pass them and another one?

+4
source share
3 answers

You can create a "parameter string". Suppose you have in your code:

 my_view( request, page, options): sort_choices = {P:'price',N:'name', ...} n_item_choices = {'S':5, 'L':50, 'XL':100) ascending_descending_choices = {'A':'', 'D':'-'} ... 

then you can use concatenat options like:

 options='PSD' #order by price, 5 items per page, descending order 

encode gadgets as:

 <a href="?page={{ prev_page }}&options={{ options }}">Previous</a> 

then in urls.py capture options and in view:

 my_view( request, page, options): ... #choides .... try: optionsArray = options.split('-') sort_by = sort_choices[ optionsArray[0] ] n_ites_page = n_item_choices[ optionsArray[1] ] asc_or_desc = ascending_descending_choices[ optionsArray[2] ] ... except: somebody is playing .... 

using this method you can add additional paginations parameters without changing urls.py, all you need to do is add options at the end of the line parameters. This has advantages, but also some dangers: I hope you can identify the risks.

+2
source
+4
source

With Django Pagination - saving GET parameters is simple.

First, copy the GET parameters into the variable (in view):

 GET_params = request.GET.copy() 

and send it to the template through the context dictionary:

 return render_to_response(template, {'request': request, 'contact': contact, 'GET_params':GET_params}, context_instance=RequestContext(request)) 

The second thing you need to do is use it in the urls (href) in the template - an example (extension of the basic html pagination to handle an extra parameter):

 {% if contacts.has_next %} {% if GET_params %} <a href="?{{GET_params.urlencode}}&amp;page={{ contacts.next_page_number }}">next</a> {% else %} <a href="?page={{ contacts.next_page_number }}">next</a> {% endif %} {% endif %} 

Source - Added the same answer.

0
source

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


All Articles