【问题标题】:Django: passing variable to simple_tag other than id failsDjango:将变量传递给simple_tag而不是id失败
【发布时间】:2016-12-25 09:47:43
【问题描述】:

情况很简单:我想在这样的模板中显示一个特定的对象(模型块):{% block_by_name editorial as b %} {{ b.title }},或者最好使用像这样的过滤器{{ block.title|get_by_name:editorial }}

我用 simple_tag 成功了。

通过 id 获取项目可以正常工作:

# in templatetags
@register.simple_tag
def block_by_id(id=1):
    b = Block.objects.get(id=id)
    return b


# in html template it get block with id 3 and shows it OK
{% block_by_id 3 as b %} {{ b.title }}

但是,当我想按如下名称或标签获取块时,

按名称获取项目失败

#
@register.simple_tag
def block_by_name(n="default_name"):
    b = Block.objects.get(name=n)
    return b

# in html template it fails to get block with name "editorial"
{% block_by_name editorial as b %} {{ b.title }}

Django 显示错误Block matching query does not exist 因为它假定变量n 是空字符串,尽管我传递了它:“编辑”

回溯:

        b = Block.objects.get(name=n)

     ...

▼ Local vars
Variable    Value
n   

''

不知道为什么会这样。 如何传递变量以免它消失?

【问题讨论】:

    标签: python django django-templates django-custom-tags


    【解决方案1】:

    但是你没有通过"editorial",你通过了editorial。那是一个变量,不存在。使用字符串。

    【讨论】:

    • 谢谢!我是如此遵循不需要引号的 ID 1、2、3 的路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多