Django模板变量解析

1 投票
1 回答
573 浏览
提问于 2025-04-16 05:40

大家好,我这边刚开始接触Django一周,所以如果我的问题听起来很傻,请不要介意。我在StackOverflow和谷歌上搜索过,但没有找到答案。

我有一个简单的模型叫做Term(我正在为我的新闻模块实现标签和分类),还有一个模板标签叫taxonomy_list,它应该输出所有分配给一篇文章的术语,并以逗号分隔的链接列表显示。我的Term模型没有permalink字段,但我在视图中获取了这个字段,并将其传递给模板。在模板中,permalink的值看起来没问题,但在我的模板标签中却无法加载。

为了说明这个问题,我从我的代码中提取了一些片段。下面是我自定义的模板标签taxonomy_list:

from django import template
from juice.taxonomy.models import Term
from juice.news.models import Post

register = template.Library()

@register.tag
def taxonomy_list(parser, token):
    tag_name, terms = token.split_contents()
    return TaxonomyNode(terms)

class TaxonomyNode(template.Node):
    def __init__(self, terms):
        self.terms = template.Variable(terms)
    def render(self, context):
        terms = self.terms.resolve(context)
        links = []

        for term in terms.all():
            links.append('<a href="%s">%s</a>' % (term.permalink, term.name))

        return ", ".join(links)

这是我单篇文章的视图:

# single post view
def single(request, post_slug):
    p = Post.objects.get(slug=post_slug)
    p.tags = p.terms.filter(taxonomy='tag')
    p.categories = p.terms.filter(taxonomy='category')

    # set the permalinks
    for c in p.categories:
        c.permalink = make_permalink(c)
    for t in p.tags:
        t.permalink = make_permalink(t)

    return render_to_response('news-single.html', {'post': p})

在我的模板中,我展示了两种访问分类的方法:

Method1: {% taxonomy_list post.categories %}
Method2: {% for c in post.categories %}{{c.slug}} ({{c.permalink}}),{% endfor %}

有趣的是,方法2工作得很好,但方法1却说我的.permalink字段未定义,这可能意味着变量解析没有按我预期的那样完成,因为“额外”的permalink字段被遗漏了。

我想也许变量没有识别这个字段,因为它在模型中没有定义,所以我尝试在模型中给它一个“临时”值,但这也没有帮助。方法1的链接中包含了“临时”,而方法2则正常工作。

有没有什么想法?

谢谢!

1 个回答

2

这其实不是关于变量解析的问题。关键在于你是如何从 Post 对象中获取这些术语的。

当你在模板标签中写 for term in terms.all() 时,all 这个部分是在告诉 Django 重新评估查询集,这意味着要再次查询数据库。所以,你之前精心标注的术语会被数据库中的新对象刷新,而 permalink 属性也会被覆盖。

如果你去掉 all,只写 for term in terms:,那可能就能正常工作了。这样做会重用已有的对象。

撰写回答