0

情况很简单:我想在这样的模板中显示一个特定的对象(模型块):{% 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   

''

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

4

1 回答 1

1

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

于 2016-08-18T12:49:14.873 回答