Django templatess中{%url%}标记中的随机参数数量

2024-05-06 12:37:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想为我的英语不好道歉。 (我来自俄罗斯)

所以,我想在我的网站上添加分页。 想象一下,我们有两个页面:site.com/(作为主页),上面有帖子列表, 和site.com/tag/tagname-按标签发布列表

两页都必须有分页器。 我想为分页块paginator.html创建单独的模板,并将其包含在index.htmltag.html

页面URL必须如下所示:site.com/5site.com/tag/tagname/5。因此,我们对{%url%}标记有不同数量的参数:1用于主页,2用于标记页

举个简单的例子:

url.py:

app_name = 'test_app'
urlpatterns = [
    url(r'^$', views.index, name = 'index'),
    url(r'^(?P<page_num>[0-9]+)$', views.index, name = 'index'),
    url(r'^tag/(?P<tag_name>[-\w]+)$', views.tag, name = 'tag'),
    url(r'^tag/(?P<tag_name>[-\w]+)/(?P<page_num>[0-9]+)$', views.tag, name = 'tag'),
]

视图.py

def paginate(objects_list, in_page, page_num):
    paginator = Paginator(objects_list, in_page)
    page = paginator.page(page_num)
    return page

def index(request, page_num = 1):
    page = paginate(questions, 5, page_num)
    return render(request, 'test_app/index.html', {
        'questions': page,
    })

def tag(request, tag_name, page_num = 1):
    page = paginate(questions, 5, page_num)
    return render(request, 'test_app/tag.html', {
        'questions': page,
        'tag_name': tag_name,
    })

问题是一系列问题

index.html

{% for question in questions %}
    Author: {{ question.author }} <br>
    Title: {{ question.title }} <br>
    Body: {{ question.body }} <br>
{% endfor %}

{% load i18n %}
{% trans "test_app:index" as page_url %}
{% include "./paginator.html" %}

tag.html

Posts by tag: {{ tag_name }} <br> <br>
{% for question in questions %}
    Author: {{ question.author }} <br>
    Title: {{ question.title }} <br>
    Body: {{ question.body }} <br>
{% endfor %}

{% load i18n %}
{% trans "test_app:tag" as page_url %}
{% trans tag_name as var1 %}
{% include "./paginator.html" %}

paginator.html

{% if questions.has_previous %}
    <a href = "{% url page_url 1 %}"><button> &lt;&lt; </button></a>
    <a href = "{% url page_url var1 questions.previous_page_number %}"><button> {{ questions.previous_page_number }} </button></a>
{% endif %}

<a><button> {{ questions.number }} </button></a>

{% if questions.has_next %}
    <a href = "{% url page_url var1 questions.next_page_number %}"><button> {{ questions.next_page_number }} </button></a>
    <a href = "{% url page_url var1 questions.paginator.num_pages %}"><button> &gt;&gt; </button></a>
{% endif %}

我试着运行这个例子。它适用于tag.html

对于index.html,我有以下消息:

NoReverseMatch at /test/ Reverse for 'index' with arguments '('', 2)' and keyword arguments '{}' not found. 2 pattern(s) tried: ['test/(?P[0-9]+)$', 'test/$']

我的问题也是如此。 如何使用{%url%}标记,像paginator.html一样在tamplate内部,如果我不知道,我当前的url包含多少个参数

另外,我只想在paginator.html中使用变量名而不是“questions”

我试过这个:

我在tag.html和index.html中写道: {%trans question as page\u object%}

在paginator.html中使用“page\u object”而不是“questions”。但我有个错误信息:

'Page' object has no attribute 'replace'

{% trans question as page_object %}

我试过几个变种,但都不管用。我不知道,我还能做什么

我不想在每一页都粘贴分页器


Tags: nametestbrappurltransindexhtml