我想在我的网站上显示出版物列表;但是,我还想显示一个标题,说明该特定年份发布的每组出版物的年份。
所以我希望我的最终结果是这样的(我的声誉是 1 :(我无法上传图片):
https://dl.dropboxusercontent.com/u/10752936/Screen%20Shot%202013-06-21%20at%206.00.15%20PM.png
我有一张三列的桌子;id (primary key), title (the title of the article), and date (the date of publications)
在我的模板文件中;执行以下操作将在每篇文章之前打印标题:
{% for curr_pub in all_publications %}
<h1>{{ curr_pub.date.year }}</h1>
<li>{{ curr_pub.title }}</li>
{% endfor %}
我正在传递all_publications
命令,'-date'
这意味着我可以将当前行的年份与前一行进行比较,curr_pub
并检查它是否不同;并相应地打印(或不打印)标题。然而,我似乎无法在模板中做到这一点。
由于我是 Django 和 Python 的新手,我不知道该怎么做,这就是我需要帮助的地方;我的想法如下:
1)在model
(def is_it_first_publication(self):
)中添加一个返回true
或的函数false
- 但我真的无法做到这一点:| - ...我不确定这是否是我需要做的!
2)第二个是在中做view
,并将额外的变量传递给模板;这是一个示例(在这种情况下效果很好):
在视图中:
def publications(request):
all_publications = Publications.objects.order_by('-date')
after_first_row_flag = False
f_year = 'Null'
list_of_ids_of_first_publications = []
for curr_pub in all_publications:
if after_first_row_flag:
if curr_pub.date.year != f_year:
list_of_ids_of_first_publications.append(curr_pub.id)
f_year = curr_pub.date.year
else:
# The year of first (or earliest) publication has to be added
#
list_of_ids_of_first_publications.append(curr_pub.id)
f_year = curr_pub.date.year
after_first_row_flag = True
template = loader.get_template('counters/publications.html')
context = RequestContext(request, {
'all_publications': all_publications,
'list_of_first_publications': list_of_ids_of_first_publications,
})
return HttpResponse(template.render(context))
在模板中:
{% for curr_pub in all_publications %}
{% if curr_pub.id in list_of_first_publications %}
<h1> {{ curr_pub.date.year }} </h1>
{% endif %}
<li> Placeholder for [curr_pub.title] </li>
{% endfor %}