Django-使用多个GET参数在模板中分页 [英] Django - Paginating in Template using multiple GET parameters

查看:60
本文介绍了Django-使用多个GET参数在模板中分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django Paginator,并且我想拥有多个可用的get参数,例如:第1页sort_by =价格

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

但是,在我的模板标签中,我有:

However, in my template tags I have:

Showing items sorted by {{ SORT_PARAM }}.
Showing {{ ITEMS_PER_PAGE }} items per page.

{% if has_prev %}
<a href="?page={{ prev_page }}">Previous</a> |
{% endif %}

但是,这不会保留其他GET变量.我的意思是,如果我正在查看

However, this does not preserve the other GET variables. What I mean is, if I'm viewing

page/?page=1&sort_by=price

然后单击上面模板片段中的链接,我将转到

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

page=2

代替

page=2&sort_by=price

我的意思是,a href不会保留其他GET参数.

What I mean is, the a href does not preserve the other GET parameters.

一种解决方案是我可以在a href中键入所有可能的GET参数,例如

One solution is I could type all the possible GET parameters in the a href, such as

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

但是,如果我想在浏览中添加更多参数,则扩展性将降低.我猜应该有一种自动化的方法来获取所有GET参数,然后再传递这些参数和另外一个?

but this will become less scalable the more arguments I want to add to my browsing. I'm guessing there should be an automated way to obtain all GET parameters, and then pass those and one more?

推荐答案

您可以创建参数字符串".让我们假设您的代码中有:

You can create a 'parameter-string'. Let's supose that in your code you have:

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 concatenat options as:

options='P-S-D'  #order by price, 5 items per page, descending order

将选项编码为:

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

然后,在urls.py捕获选项和视图中:

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 ....

使用此方法,您可以自由添加更多分页选项,而无需修改urls.py,您所要做的就是在字符串options的末尾附加选项.这既有优点,也有一些危险:我希望您能确定风险.

with this method you are free to add more paginations options without modify urls.py, all you need is to append options at the end of string options . This has advantages but also some dangers: I hope you can identify risks.

这篇关于Django-使用多个GET参数在模板中分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆