Unable to access Dictionary values in Template (object pk is the dict key)

别来无恙 提交于 2020-01-16 19:20:20

问题


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 keys are pks of the object).

View code that constructs the 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

I have also tried with comment_uservote[str(comment.id)] but this does not help either.

Template (that does not work):

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

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.


回答1:


No, this doesn't work, and the documentation doesn't imply that it should. You will need a custom tag or filter.



来源:https://stackoverflow.com/questions/5875894/unable-to-access-dictionary-values-in-template-object-pk-is-the-dict-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!