Django Year/Month based posts archive

前端 未结 3 428
情话喂你
情话喂你 2021-02-06 12:04

i\'m new to Django and started an application, i did the models, views, templates, but i want to add some kind of archive to the bottom of the page, something like this http:/

3条回答
  •  猫巷女王i
    2021-02-06 12:34

    Ok... so the final code that works for me is:

    in view:

     rom_months = ['Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Iun', 
    'Iul', 'Aug', 'Sept', 'Oct', 'Noi', 'Dec']
    
    def arhiva(request):
        arch = Post.objects.dates('data', 'month', order='DESC')
    
        archives = {}
    
        for i in arch:
            year = i.year
            month = i.month
            try:
                archives[year][month-1][1] = True
            except KeyError:
    
                archives[year]=[[datetime.date(year,k+1,1),False,rom] for k, rom in enumerate(rom_months)]
                archives[year][month-1][1] = True
    
        return render_to_response('blog/arhiva.html', {'archives':sorted(archives.items(),reverse=True)})
    

    and in template:

    {% for year, month_list in archives %}
        {{ year }} Arhive: 
        {% for month, has_link, rom_month in month_list %}
            {% if has_link %}{% endif %}
                 {{ rom_month }}
            {% if has_link %}{% endif %} 
        {% endfor %}
        
    {% endfor %}

    and the result:

    2009 Arhive: Ian Feb Mar Apr Mai Iun Iul Aug Sept Oct Noi Dec 
    2008 Arhive: Ian Feb Mar Apr Mai Iun Iul Aug Sept Oct Noi Dec 
    2007 Arhive: Ian Feb Mar Apr Mai Iun Iul Aug Sept Oct Noi Dec 
    2003 Arhive: Ian Feb Mar Apr Mai Iun Iul Aug Sept Oct Noi Dec 
    

    Thanks a lot again for help. You're the best! I'm the n00b! :)

提交回复
热议问题