gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:21:53 25 4
gpt4 key购买 nike

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

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

网址.py:

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

模板/别名.html:
<div>...stuff...</div>
{% include "paginator.html" %}

模板/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>
...

什么是 somemagic ?

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

最佳答案

编辑:

您需要 somemagic是具有当前 View 名称的变量。

尝试这个:

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

您可以使用 django-snippets 中的一些代码来实现这一点:
  • Variable resolving URL template tag使 {% url %} 标签从上下文解析变量。
  • Resolve URLs to view name函数resolve_to_name(path)返回 path 的 View 名称.您只需要创建一个使用此功能的过滤器。

  • 此解决方案不适用于以下网址:
    '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 返回 View 的名称及其参数作为元组,以及新的 {% url myvar %}接受这个元组并使用它来反转带有 View 名称及其参数的路径。

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

    上一个答案

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

    使用 Django 分页,对可迭代对象进行分页的代码将是:
    {% 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 可以是任何可迭代的:列表、元组、查询集等

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

    关于Django:如何获取当前 URL 标记名(用于分页)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1216285/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com