希望按月和年份制作通用视图存档页面。 像这样:
2011 - January March
2010 - October December
我得到的是什么:
2011 - January January
2010 - January January
这可能吗?以下是视图和模板。
视图
def track_archive(request):
return date_based.archive_index(
request,
date_field='date',
queryset=Track.objects.all(),
)
track_archive.__doc__ = date_based.archive_index.__doc__
template
{% for year in date_list %}
<a href="{% url track_archive %}{{ year|date:"Y" }}/">{{ year|date:"Y" }}</a> archives:
{% for month in date_list %}
<a href="{% url track_archive %}{{ year|date:"Y" }}/{{ month|date:"b" }}/">{{ month|date:"F" }}</a>
{% endfor %}
{% endfor %}
答案 0 :(得分:4)
如果您使用基于类的通用视图,则可以执行此操作并坚持使用通用视图。
而不是使用ArchiveIndexView 使用像
这样的东西class IndexView(ArchiveIndexView):
template_name="index.html"
model = Article
date_field="created"
def get_context_data(self, **kwargs):
context = super(IndexView,self).get_context_data(**kwargs)
months = Article.objects.dates('created','month')[::-1]
context['months'] = months
return context
然后在你的模板中,你会得到月份字典,你可以按年份分组::
<ul>
{% for year, months in years.items %}
<li> <a href ="{% url archive_year year %}"> {{ year }} <ul>
{% for month in months %}
<li> <a href ="{% url archive_month year month.month %}/">{{ month|date:"M Y" }}</a> </li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
答案 1 :(得分:3)
根据doc,archive_index
仅计算年份。您可能想要编写年/月分组:
def track_archive(request):
tracks = Track.objects.all()
archive = {}
date_field = 'date'
years = tracks.dates(date_field, 'year')[::-1]
for date_year in years:
months = tracks.filter(date__year=date_year.year).dates(date_field, 'month')
archive[date_year] = months
archive = sorted(archive.items(), reverse=True)
return date_based.archive_index(
request,
date_field=date_field,
queryset=tracks,
extra_context={'archive': archive},
)
您的模板:
{% for y, months in archive %}
<div>
{{ y.year }} archives:
{% for m in months %}
{{ m|date:"F" }}
{% endfor %}
</div>
{% endfor %}
y和m是日期对象,您应该能够提取任何日期格式信息以构建您的网址。