无法访问模板中的字典值(对象pk是dict键)

时间:2011-05-03 21:25:53

标签: django dictionary django-templates django-views

我有一个Django View,可以为模板构建一个字典。我看过类似的问题,但是没有人展示如何使用对象pk作为键来访问模板中的字典值(在我的例子中,key是对象的pk s )。

查看构造dict的代码:

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)],但这也无济于事。

模板(不起作用):

{% for comment in comments %}
  {{comment_uservote.comment.pk}} <!--this does not work-->
{% enfor %}

但是,如果我向pk添加任何评论comment_uservote,则以下情况有效。

模板(有效但直接替换):

{% for comment in comments %}
  {{comment_uservote.16}} <!--this works-->
{% enfor %}

感谢您的帮助。如果您需要我的更多信息,请告诉我。

1 个答案:

答案 0 :(得分:2)

不,这不起作用,文档并不意味着它应该。您需要自定义标签或过滤器。

相关问题