gpt4 book ai didi

python - Django 模板变量解析

转载 作者:行者123 更新时间:2023-12-01 06:14:37 25 4
gpt4 key购买 nike

嘿,Django 回来已经一周了,所以如果这个问题很愚蠢,请不要介意我,尽管我在 stackoverflow 和 google 上搜索过,但没有运气。

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

为了说明这一点,我从代码中获取了一些信息。这是我的自定义模板标签,名为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)

这是我的单个帖 subview :

# 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 运行正常。

有什么想法吗?

谢谢!

最佳答案

这实际上并不是变量分辨率的问题。问题在于如何从 Post 对象获取术语。

当您在模板标签内执行 for term in terms.all() 时,all 会告诉 Django 重新评估查询集,这意味着查询再次数据库。因此,您仔细注释的术语将被数据库中的新对象刷新,并且永久链接属性将被覆盖。

如果你只是删除全部,它可能会起作用 - 所以你只有术语:。这将重用现有的对象。

关于python - Django 模板变量解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3957977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com