Django:如何获取当前 URL 标记名(用于分页)?

发布于 2024-07-30 20:03:20 字数 778 浏览 3 评论 0原文

我正在尝试使用 URL 中的 page 参数(而不是 GET 参数)进行分页。 我还希望我的分页能够在多个不同模板之间共享代码。

鉴于此,我想我需要做这样的事情:

urls.py:

url(r'^alias/page;(?P<page>[0-9]+)/(?P<id>.*)$', alias.get, name="alias"),

tempaltes/alias.html:

<div>...stuff...</div>
{% include "paginator.html" %}

templates/paginator.html :

{% if page_obj.has_previous or page_obj.has_next %}
{% load filters %}
<div class="pagination clear">
    {% if page_obj.has_previous %}
        <a href="{% url somemagic %}" class="prev">&lsaquo;&lsaquo; previous</a>
...

What is somemagic?

假设我想保持我的网址相同,除了设置页面 page_obj.previous_page_number

I'm trying to do pagination with the page parameter in the URL (instead of the GET parameter). I also want my pagination to be shared code across multiple different templates.

Given that, I think I need to do something like this :

urls.py:

url(r'^alias/page;(?P<page>[0-9]+)/(?P<id>.*)

tempaltes/alias.html:

<div>...stuff...</div>
{% include "paginator.html" %}

templates/paginator.html :

{% if page_obj.has_previous or page_obj.has_next %}
{% load filters %}
<div class="pagination clear">
    {% if page_obj.has_previous %}
        <a href="{% url somemagic %}" class="prev">‹‹ previous</a>
...

What is somemagic?

Assume I want to keep my url the same except set the page page_obj.previous_page_number

, alias.get, name="alias"),

tempaltes/alias.html:

templates/paginator.html :

What is somemagic?

Assume I want to keep my url the same except set the page page_obj.previous_page_number

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一口甜 2024-08-06 20:03:21

它将类似于以下内容。 但我不知道你所说的 id 是什么意思,所以我只是输入了一个通用对象 id。 url 的语法是 {% url view_name param1 param2 ... %}

{% url alias page_obj.previous_page_number object.id %}

根据您的需要更新:

{% url alias page_obj.previous_page_number object.id as prev_url %}
{% include "paginator.html" %}
...
{% if page_obj.has_previous %}
        <a href="{{prev_url}}" class="prev">‹‹ previous</a>

It will be something like the following. Except I don't know what you mean by id so I just put a generic object id. The syntax for url is {% url view_name param1 param2 ... %}

{% url alias page_obj.previous_page_number object.id %}

Updated base on your need:

{% url alias page_obj.previous_page_number object.id as prev_url %}
{% include "paginator.html" %}
...
{% if page_obj.has_previous %}
        <a href="{{prev_url}}" class="prev">‹‹ previous</a>
风情万种。 2024-08-06 20:03:20

编辑:

您需要somemagic作为具有当前视图名称的变量。

试试这个:

{% with request.path_info|resolve_url_name as current_view %}
    {% url current_view page_obj.previous_page_number object.id %}
{% endwith %}

您可以使用 django-snippets 中的一些代码来实现此功能:

  1. 变量解析 URL 模板标记 使 {% url %} 标签解析上下文中的变量。
  2. 解析 URL 以查看名称 函数 resolve_to_name(path) 返回path 的视图名称。 您只需要创建一个使用此函数的过滤器。

此解决方案不适用于以下网址:

'alias/param1_regexp/param2_regexp/page;(?P<page>[0-9]+)/(?P<id>.*)

因为您不知道 param1 和 param2。

可以对上面的 django-snippets 进行修改,以使这种 url 起作用:

第一个片段修改:

from django.template import defaulttags, VariableDoesNotExist, Variable

class ResolvingURLNode(defaulttags.URLNode):
    def render(self, context):
        original_view_name = self.view_name
        try:
            resolved = Variable(self.view_name).resolve(context)
            if len(resolved) > 1:                
                self.view_name = resolved[0]
                if resolved[1]:
                    self.args = [Variable(arg) for arg in resolved[1]]
            elif len(resolved) > 0:
                self.view_name = resolved[0]
            else:
                self.view_name = resolved

        except VariableDoesNotExist:
            pass
        ret = super(defaulttags.URLNode, self).render(context)
        # restore view_name in case this node is reused (e.g in a loop) in
        # which case the variable might resolve to something else in the next iteration)
        self.view_name = original_view_name
        return ret

defaulttags.URLNode = ResolvingURLNode

第二个片段修改

from django.core.urlresolvers import RegexURLResolver, RegexURLPattern, Resolver404, get_resolver

__all__ = ('resolve_to_name',)

def _pattern_resolve_to_name(self, path):
    match = self.regex.search(path)
    if match:
        name = ""
        if self.name:
            name = self.name
        elif hasattr(self, '_callback_str'):
            name = self._callback_str
        else:
            name = "%s.%s" % (self.callback.__module__, self.callback.func_name)
        if len(match.groups()) > 0:
            groups = match.groups()
        else:
            groups = None
        return name, groups


def _resolver_resolve_to_name(self, path):
    tried = []
    match = self.regex.search(path)
    if match:
        new_path = path[match.end():]
        for pattern in self.url_patterns:
            try:
                resolved = pattern.resolve_to_name(new_path)
                if resolved:
                    name, groups = resolved
                else:
                    name = None
            except Resolver404, e:
                tried.extend([(pattern.regex.pattern + '   ' + t) for t in e.args[0 ['tried']])
            else:
                if name:
                    return name, groups
                tried.append(pattern.regex.pattern)
        raise Resolver404, {'tried': tried, 'path': new_path}


# here goes monkeypatching
RegexURLPattern.resolve_to_name = _pattern_resolve_to_name
RegexURLResolver.resolve_to_name = _resolver_resolve_to_name


def resolve_to_name(path, urlconf=None):
    return get_resolver(urlconf).resolve_to_name(path)

基本上,resolve_to_name 返回视图的名称,并且它的参数是一个元组,new {% url myvar %} 接受这个元组并使用它来反转具有视图名称及其参数的路径。

如果您不喜欢过滤器方法,也可以使用自定义中间件来完成。


上一个答案

您应该检查 django-pagination,它是一个非常好的 django 应用程序,易于使用并完成工作。

使用 django 分页,对可迭代对象进行分页的代码将是:

{% load pagination_tags %}

{% autopaginate myiterable 10 %}

<代码>{% for item in myiterable %}
渲染内容
{% endfor %}

{% paginate %}

myiterable可以是任何可迭代的:列表、元组、查询集等

googlecode 的项目页面:
http://code.google.com/p/django-pagination/

因为您不知道 param1 和 param2。

可以对上面的 django-snippets 进行修改,以使这种 url 起作用:

第一个片段修改:

第二个片段修改

基本上,resolve_to_name 返回视图的名称,并且它的参数是一个元组,new {% url myvar %} 接受这个元组并使用它来反转具有视图名称及其参数的路径。

如果您不喜欢过滤器方法,也可以使用自定义中间件来完成。


上一个答案

您应该检查 django-pagination,它是一个非常好的 django 应用程序,易于使用并完成工作。

使用 django 分页,对可迭代对象进行分页的代码将是:

{% load pagination_tags %}

{% autopaginate myiterable 10 %}

<代码>{% for item in myiterable %}
渲染内容
{% endfor %}

{% paginate %}

myiterable可以是任何可迭代的:列表、元组、查询集等

googlecode 的项目页面:
http://code.google.com/p/django-pagination/

Edit:

You need somemagic to be a variable with the name of the current view.

Try this:

{% with request.path_info|resolve_url_name as current_view %}
    {% url current_view page_obj.previous_page_number object.id %}
{% endwith %}

You can get this working with some code from django-snippets:

  1. Variable resolving URL template tag Makes the {% url %} tag resolve variables from context.
  2. Resolve URLs to view name The function resolve_to_name(path) returns the view name for path. You just need to create a filter that uses this function.

This solution wont work with urls like:

'alias/param1_regexp/param2_regexp/page;(?P<page>[0-9]+)/(?P<id>.*)

because you've no clue about param1 and param2.

A modification can be done to the django-snippets above to make this kind of urls work:

First snippet modifications:

from django.template import defaulttags, VariableDoesNotExist, Variable

class ResolvingURLNode(defaulttags.URLNode):
    def render(self, context):
        original_view_name = self.view_name
        try:
            resolved = Variable(self.view_name).resolve(context)
            if len(resolved) > 1:                
                self.view_name = resolved[0]
                if resolved[1]:
                    self.args = [Variable(arg) for arg in resolved[1]]
            elif len(resolved) > 0:
                self.view_name = resolved[0]
            else:
                self.view_name = resolved

        except VariableDoesNotExist:
            pass
        ret = super(defaulttags.URLNode, self).render(context)
        # restore view_name in case this node is reused (e.g in a loop) in
        # which case the variable might resolve to something else in the next iteration)
        self.view_name = original_view_name
        return ret

defaulttags.URLNode = ResolvingURLNode

Second snippet modifications

from django.core.urlresolvers import RegexURLResolver, RegexURLPattern, Resolver404, get_resolver

__all__ = ('resolve_to_name',)

def _pattern_resolve_to_name(self, path):
    match = self.regex.search(path)
    if match:
        name = ""
        if self.name:
            name = self.name
        elif hasattr(self, '_callback_str'):
            name = self._callback_str
        else:
            name = "%s.%s" % (self.callback.__module__, self.callback.func_name)
        if len(match.groups()) > 0:
            groups = match.groups()
        else:
            groups = None
        return name, groups


def _resolver_resolve_to_name(self, path):
    tried = []
    match = self.regex.search(path)
    if match:
        new_path = path[match.end():]
        for pattern in self.url_patterns:
            try:
                resolved = pattern.resolve_to_name(new_path)
                if resolved:
                    name, groups = resolved
                else:
                    name = None
            except Resolver404, e:
                tried.extend([(pattern.regex.pattern + '   ' + t) for t in e.args[0 ['tried']])
            else:
                if name:
                    return name, groups
                tried.append(pattern.regex.pattern)
        raise Resolver404, {'tried': tried, 'path': new_path}


# here goes monkeypatching
RegexURLPattern.resolve_to_name = _pattern_resolve_to_name
RegexURLResolver.resolve_to_name = _resolver_resolve_to_name


def resolve_to_name(path, urlconf=None):
    return get_resolver(urlconf).resolve_to_name(path)

Basically, resolve_to_name returns the name of the view and it's parameters as a tuple, and the new {% url myvar %} takes this tuple and uses it to reverse the path with the view name and it's parameters.

If you don't like the filter approach it can also be done with a custom middleware.


Previous answer

You should check django-pagination, it's a really nice django application, easy tu use and gets the job done.

With django pagination the code to paginate an iterable would be:

{% load pagination_tags %}

{% autopaginate myiterable 10 %} <!-- 10 elements per page -->

{% for item in myiterable %}
RENDERING CONTENT
{% endfor %}

{% paginate %} <!-- this renders the links to navigate through the pages -->

myiterable can be anything that is iterable:list, tuple, queryset, etc

The project page at googlecode:
http://code.google.com/p/django-pagination/

because you've no clue about param1 and param2.

A modification can be done to the django-snippets above to make this kind of urls work:

First snippet modifications:

Second snippet modifications

Basically, resolve_to_name returns the name of the view and it's parameters as a tuple, and the new {% url myvar %} takes this tuple and uses it to reverse the path with the view name and it's parameters.

If you don't like the filter approach it can also be done with a custom middleware.


Previous answer

You should check django-pagination, it's a really nice django application, easy tu use and gets the job done.

With django pagination the code to paginate an iterable would be:

{% load pagination_tags %}

{% autopaginate myiterable 10 %} <!-- 10 elements per page -->

{% for item in myiterable %}
RENDERING CONTENT
{% endfor %}

{% paginate %} <!-- this renders the links to navigate through the pages -->

myiterable can be anything that is iterable:list, tuple, queryset, etc

The project page at googlecode:
http://code.google.com/p/django-pagination/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文