2011-02-16 32 views
0

尋求按月份和年份製作通用視圖歸檔頁面。 像這樣:Django具有通用視圖的年份/月歸檔頁面

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 %} 

回答

3

按照docarchive_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日期的對象,你應該能夠提取任何日期格式的信息來構建您的網址。

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>