具有查询参数的Django URL模板

Bja*_*rte 5 django django-templates

我正在尝试通过我的视图将查询参数传递到链接中,但这使我无法很好地实现这一目标。

我的模板如下:

<a class="link-button" href="{% url 'videos:index' %}?tag={{ tag }}&page={{ next }}">Next</a>
Run Code Online (Sandbox Code Playgroud)

这返回了我想要的:

http://127.0.0.1:8000/videos/?tag=1&page=2
Run Code Online (Sandbox Code Playgroud)

虽然这样做有效,但它非常脆弱,无法处理None值,因此必须有一种更好的方法。

我试图通过urltemplate标记传递它,但它似乎不是我想要的,因为它需要更改url配置的路径:

{% url 'videos:index' page=next tag=tag %}
Run Code Online (Sandbox Code Playgroud)

是否有执行此操作的实际方法或可以用来获取参数的模板标签?我尝试搜索它,但是它给了我很多旧结果,并且提供了更多路径URL,例如:/videos/page-1/tag-1/我不需要的。

我希望做这样的事情:

<a href="{% url 'videos:index'}?{% params page=next tag=tag %}">Next</a>
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 10

没有内置的支持,但你可以自己添加一个。例如,您可以定义以下模板标记。例如,我们可以用粗体构建文件:

app/
    templatetags/
        __init__.py
        urlparams.py
Run Code Online (Sandbox Code Playgroud)

其中urlparams.py,我们定义:

from django import template
from urllib.parse import urlencode

register = template.Library()

@register.simple_tag
def urlparams(*_, **kwargs):
    safe_args = {k: v for k, v in kwargs.items() if v is not None}
    if safe_args:
        return '?{}'.format(urlencode(safe_args))
    return ''
Run Code Online (Sandbox Code Playgroud)

在模板中,我们可以加载模板标签,然后像这样使用它:

{% load urlparams %}

<a href="{% url 'videos:index'}{% urlparams page='1' tag='sometag' %}">Next</a>
Run Code Online (Sandbox Code Playgroud)

请注意,严格来说,URL 参数可以多次包含相同的键。这是在这里没有可能。所以我们不能生成所有可能的URL 参数,但这通常很少见,在我看来,这首先不是一个好主意。