Django模板可变分辨率

时间:2010-10-18 09:40:56

标签: python django

嘿那里,Django回到这里已经有一个星期了,所以如果问题很愚蠢,请不要介意我,尽管我搜索了stackoverflow并没有运气谷歌。

我有一个名为Term的简单模型(试图为我的新闻模块实现标签和类别),我有一个名为taxonomy_list的模板标签,它应该以逗号分隔的链接列表输出分配给帖子的所有术语。现在,我的Term模型没有永久链接字段,但它从我的视图中获取并传递给模板。永久链接值在模板内部看起来很好,但不会加载到我的模板标记中。

为了说明这一点,我从代码中得到了一些内容。这是我的自定义模板标签,名为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字段未定义,这可能意味着变量分辨率没有像我期望的那样完成,因为“额外”永久链接字段是遗漏了。

我认为可能变量没有识别该字段,因为它没有在模型中定义,所以我尝试在模型中为其分配一个“临时”值,但这也没有帮助。方法1在链接中包含“临时”,而方法2正在正确运行。

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

这不是一个可变分辨率的问题。问题是如何从Post对象中获取术语。

当您在模板标记中执行for term in terms.all()时,all告诉Django重新评估查询集,这意味着再次查询数据库。因此,您的精心注释的术语将使用数据库中的新对象进行刷新,并且permalink属性将被覆盖。

如果您放弃all,它可能会有效 - 所以您只有for term in terms:。这将重用现有对象。