Django:将变量传递给 id 以外的 simple_tag 失败

Django: passing variable to simple_tag other than id fails

情况很简单:我想在这样的模板中显示特定对象(模型块):{% 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 是空字符串,尽管我传递了它:"editorial"

回溯:

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

     ...

▼ Local vars
Variable    Value
n   

''

不确定为什么会这样。 我怎样才能传递变量以使其不消失?

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