如何在Django模板中访问键的值?

时间:2012-06-03 14:55:34

标签: django django-templates django-views

新手问题: 我在views.py

中定义的方法中使用extra_Context进行字典渲染

我的观点:

 extra_context = {
    'comment': comment
    }
return direct_to_template(request, 'events/comment_detail.html', extra_context)

如果我打印comment它打印如下:

[{'comment': u'first', 'user': 2}, {'comment': u'second', 'user': 2}]

我想将此词典传递给我的模板。我尝试使用以下代码:

       <tbody>
            {% for obj in comment %}
                {% for key,val in obj.items %}
             <tr class="{% cycle 'odd' 'even' %}">
                <td> {{val}}</td>
            </tr>
                {% endfor %}
            {% endfor %}
       </tbody>

打印:

first
2
second
2

我想这样:

first  2
second 2

..等等

我应该如何添加它以获得如上所述?

更新了!

 def comment_detail(request, object_id):
     comment_obj = EventComment.objects.filter(event = object_id)
     comment = comment_obj.values('comment','user')
     extra_context = {
         'comment': comment
         }
     return direct_to_template(request, 'events/comment_detail.html', extra_context)

comment_detail.html

<form action="" method="POST">
<table>
    <thead>
        <tr><th>{% trans "Comments" %}</th><th>{% trans "Timestamp "%}<th>{% trans "User" %}</th></tr>
    </thead>
    <tbody>
        {% if comments %}
    {% for com in comment %}
                <td> {{com.comment}}</enter code heretd>
                <td> {{com.user}}</td>
    {% endfor %}
    {% else %}
     <td> No comments </td>
     {% endif %}
    </tr>  
    </tbody>
</table>
 </form>

3 个答案:

答案 0 :(得分:2)

您不需要嵌套for迭代k,v。我刚试过这个:

查看:

def testme(request):
   comments = []
   comments.append({'user': 2, 'comment': 'cool story bro'})
   comments.append({'user': 7, 'comment': 'yep. cool story'})

   extra_context = {
      'comments': comments
   }

   return render_to_response('testapp/testme.html', extra_context )

模板:

{% if comments %}
   <b>Comments:</b>
   <ul>
   {% for comment in comments %}
     <li>{{ comment.comment }} (id {{ comment.user }})</li>
   {% endfor %}
   </ul>
{% else %}
   <b>No comments</b>
{% endif %}

答案 1 :(得分:1)

“for k(k = key),v(v = value)in object.items”

所有这一切都是在object.items中迭代每个键值对,例如name = models.CharField(max_length = 50)。您的视图已返回object.items的上下文,其中每个项目都是模型实例,并且具有一组与之关联的k,v对。

答案 2 :(得分:0)

看起来你的问题只是关于html标记。 试试这个:

<tbody>
    {% for obj in comment %}
        <tr class="{% cycle 'odd' 'even' %}">
            {% for key,val in obj.items %}          
                <td>{{val}}</td>       
            {% endfor %}
        </tr>
    {% endfor %}
</tbody>

或者这个:

<tbody>
    {% for obj in comment %}
        <tr class="{% cycle 'odd' 'even' %}"><td>
            {% for key,val in obj.items %}          
                 {{val}}<span> </span>  
            {% endfor %}
        </td>  </tr>
    {% endfor %}
</tbody>