如何使用其他get变量分页Django? [英] How to paginate Django with other get variables?
问题描述
在 Django 中使用分页时遇到问题。以下面的URL为例:
I am having problems using pagination in Django. Take the URL below as an example:
http://127.0.0.1:8000/users/?sort=first_name
在此页面上,我们按照first_name对用户列表进行排序。没有排序GET变量,它默认按照id排序。
On this page I sort a list of users by their first_name. Without a sort GET variable it defaults to sort by id.
现在,如果我点击下一个链接,我希望有以下URL:
Now if I click the next link I expect the following URL:
http://127.0.0.1:8000/users/?sort=first_name&page=2
相反,我失去所有的变量,最终得到
Instead I lose all get variables and end up with
http://127.0.0.1:8000/users/?page=2
这是一个问题,因为第二页按id而不是first_name排序。
This is a problem because the second page is sorted by id instead of first_name.
如果我使用request.get_full_path,我最终会得到一个丑陋的网址:
If I use request.get_full_path I will eventually end up with an ugly URL:
http://127.0.0.1:8000/users/?sort=first_name&page=2&page=3&page=4
什么是解决方案?有没有办法访问模板上的GET变量并替换页面的值?
What is the solution? Is there a way to access the GET variables on the template and replace the value for the page?
我正在使用分页,如 Django的文档,我的偏好是继续使用它。我使用的模板代码与此类似:
I am using pagination as described in Django's documentation and my preference is to keep using it. The template code I am using is similar to this:
{% if contacts.has_next %}
<a href="?page={{ contacts.next_page_number }}">next</a>
{% endif %}
推荐答案
提出的自定义标签太复杂,这就是我在模板中所做的:
I thought the custom tags proposed were too complex, this is what I did in the template:
<a href="?{% url_replace request 'page' paginator.next_page_number %}">
标签功能:
@register.simple_tag
def url_replace(request, field, value):
dict_ = request.GET.copy()
dict_[field] = value
return dict_.urlencode()
如果url_param还没有在url,它将添加值。如果已经存在,它将被新值替换。这是一个简单的解决方案,适合我,但是当url具有多个具有相同名称的参数时不起作用。
If the url_param is not yet in the url, it will be added with value. If it is already there, it will be replaced by the new value. This is a simple solution the suits me, but does not work when the url has multiple parameters with the same name.
您还需要将RequestContext请求实例提供给你的模板从你的看法。更多信息:
You also need the RequestContext request instance to be provided to your template from your view. More info here:
http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/
这篇关于如何使用其他get变量分页Django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!