如何在模板中迭代字典对象

时间:2014-11-16 12:53:55

标签: django django-templates

代码

engine.py ==>

class YearGroupCount():
    def __init__(self, year, count, months):
        self.year = year
        self.count = count
        self.months = months


class MonthGroupCount():
    def __init__(self, month, count):
        self.month = month
        self.month_name = calendar.month_name[month]
        self.count = count


class BlogCountsEngine():
    def __init__(self):
        self.year_group_counts = {}

    def _add_date(self, year, month):
        if str(year) in self.year_group_counts:
            year_obj = self.year_group_counts[str(year)]
        else:
            year_obj = YearGroupCount(year, 0, {})
        year_obj.count += 1

        if str(month) in year_obj.months:
            month_obj = year_obj.months[str(month)]
        else:
            month_obj = MonthGroupCount(month, 0)
        month_obj.count += 1
        year_obj.months[str(month)] = month_obj
        self.year_group_counts[str(year)] = year_obj

    def get_calculated_blog_count_list(self):
        if not Blog.objects.count():
            retval = {}
        else:
            for blog in Blog.objects.all().order_by('-posted'):
                self._add_date(blog.posted.year, blog.posted.month)
            retval = self.year_group_counts
        return retval

views.py ==>

def outer_cover(request):
    archives = BlogCountsEngine().get_calculated_blog_count_list()
    retdict = {
        'categories': Category.objects.all(),
        'posts': posts,
        'archives': archives,
    }
    return render_to_response('blog/blog_list.html', retdict, context_instance=RequestContext(request))

模板html ==>

        <div class="well">
            <h4>Arşivler</h4>
            <ul>
                {% if archives %}
                    {% for y_key, yr in archives %}
                        <li>{{ yr.year }} &nbsp;({{ yr.count }})</li>
                        {% for m_key,mth in yr.months %}
                            <li>&nbsp;&nbsp; - {{ mth.month_name }} &nbsp; ({{ mth.count }})</li>
                        {% endfor %}
                    {% endfor %}

                {% endif %}
            </ul>

        </div>

问题: 我正在用django建立自己的博客。我想迭代存档以在主页面中显示它们但我无法访问实例&#39;字典中的属性

当我在此处运行代码时,结果html为==&gt;

<div class="well">
<h4>Arşivler</h4>
<ul>
<li>  ()</li>
</ul>
</div>

我错过了什么或做错了什么?

1 个答案:

答案 0 :(得分:1)

您可以使用dict.items方法。在python 2.x中,最好使用dict.iteritems

{% for y_key, yr in archives.items %}
    <li>{{ yr.year }} &nbsp;({{ yr.count }})</li>
    {% for m_key, mth in yr.months.items %}
        <li>&nbsp;&nbsp; - {{ mth.month_name }} &nbsp; ({{ mth.count }})</li>
    {% endfor %}
{% endfor %}