如何使用其他 get 变量对 Django 进行分页? [英] How to paginate Django with other get variables?

查看:22
本文介绍了如何使用其他 get 变量对 Django 进行分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Django 中使用分页时遇到问题.以下面的网址为例:

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

在此页面上,我按用户名对用户列表进行排序.如果没有 sort 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.

现在,如果我点击下一个链接,我会看到以下网址:

Now if I click the next link I expect the following URL:

http://127.0.0.1:8000/users/?sort=first_name&page=2

相反,我丢失了所有 get 变量并以

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 我最终会得到一个丑陋的 URL:

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/获取请求上下文您的模板/

这篇关于如何使用其他 get 变量对 Django 进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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