无法访问模板中的字典值(对象pk是字典键) [英] Unable to access Dictionary values in Template (object pk is the dict key)
问题描述
我有一个Django View,该视图构造了模板的字典.我见过类似的问题,但是没有人显示如何使用对象pk
作为键来访问模板中的字典值(在我的情况下,key
是对象的pk
).
I have a Django View that constructs a dictionary to a template. I have seen similar questions but no one shows how to access the dictionary value in the template using the object pk
as the key (in my case the key
s are pk
s of the object).
查看构建字典的代码:
comment_uservote = {}
if not current_logged_user.is_anonymous():
for comment in comments_all:
try:
co_vote = Vote.objects.get(user=current_logged_user, comment=comment)
comment_uservote[comment.id] = co_vote.vote
except Vote.DoesNotExist:
co_vote = ''
comment_uservote[comment.id] = co_vote
我也尝试过使用comment_uservote[str(comment.id)]
,但这也无济于事.
I have also tried with comment_uservote[str(comment.id)]
but this does not help either.
模板(无效):
{% for comment in comments %}
{{comment_uservote.comment.pk}} <!--this does not work-->
{% enfor %}
但是,如果我将任何注释的pk
添加到comment_uservote
,则以下操作有效.
However, the following works if I add any comment's pk
to the comment_uservote
.
模板(可以工作,但可以直接替换):
Template (that works but if a direct substitution):
{% for comment in comments %}
{{comment_uservote.16}} <!--this works-->
{% enfor %}
感谢您的帮助.如果您需要我提供更多信息,请告诉我.
Appreciate your help. Please let me know if you need something more from me.
推荐答案
不,这不起作用,并且文档中并不暗示应该这样做.您将需要一个自定义标签或过滤器.
No, this doesn't work, and the documentation doesn't imply that it should. You will need a custom tag or filter.
这篇关于无法访问模板中的字典值(对象pk是字典键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!