具有查询参数的Django网址模板 [英] Django url template with query parameters

查看:73
本文介绍了具有查询参数的Django网址模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过视图将查询参数传递到链接中,但是它使我无法真正有效地实现此目的。

I'm trying to pass query parameters via my view into a link, but it escapes me on how to actually achieve this in a good way.

我的模板如下所示:

<a class="link-button" href="{% url 'videos:index' %}?tag={{ tag }}&page={{ next }}">Next</a>

这将返回我想要的内容:

This returns what I want:

http://127.0.0.1:8000/videos/?tag=1&page=2

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

While this works, it's quite fragile, does not handle None values and there must be a better way of doing this.

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

I tried to pass this via the urltemplate tag but it did not seem to be what I was looking for since it requires url config changes for path:

{% url 'videos:index' page=next tag=tag %}

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

Is there an actual way of doing this or a template tag I can use to get the parameters? I tried searching for this but it gave me a lot of old results and more path urls, like: /videos/page-1/tag-1/ which I'm not looking for.

我希望这样做:

<a href="{% url 'videos:index'}?{% params page=next tag=tag %}">Next</a>


推荐答案

没有内置功能支持,但您可以自己添加一个人。例如,您可以定义以下模板标记。例如,我们可以用黑体字构造文件:

There is no builtin support, but you can add one yourself. You can for example define the following template tag. We can for example construct files in boldface:

app/
    templatetags/
        __init__.py
        urlparams.py

其中 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 ''

在模板中,我们可以加载模板标签,然后将其与以下标签一起使用:

In the template, we can then load the template tag and then use it like with:

{% load urlparams %}

<a href="{% url 'videos:index'}{% urlparams page='1' tag='sometag' %}">Next</a>

请注意,严格来讲,URL参数可以包含 same 键乘号时报。在这里不可能。因此我们无法生成所有可能的 URL参数,但这通常很少见,我认为这并不是一个好主意。

Note that strictly speaking, the URL parameters can contain the same key multiple times. This is here not possible. So we can not generate all possible URL parameters, but this is usually quite rare, and in my opinion not a good idea in the first place.

这篇关于具有查询参数的Django网址模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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