Creating a news archive in Django

By : Udders

I looking to build a news archive in python/django, I have no idea where to start with it though. I need the view to pull out all the news articles with I have done I then need to divide them in months and years so e.g.

Sept 09 Oct 09

I then need in the view to some every time a new news article is created for a new month it needs to output the new month, so if a news article was written in November the archive would then be,

Sept 09 Oct 09 Nov 09

Any one help?

By : Udders


It seems like you are trying to make a single view that pulls out of of the data and then try to order them by dates ect. I don't think that would be the best way to go about this.

Instead what you could do is to make a view to display each month's articles. I don't know your models but something like:

articles = ArticleModel.objects.filter(date__month=month, date__year=year)

the month and year you would get from your url, fx archive/2009/9.

If you want to make sure that you only display your links to archives that has content, an easy solution would be to get all the articles and flag the months that has content. There should be a better way to do that, but if you put it inside a middleware and cache it, it shouldn't be a problem though.

An excellent place to start is the book Practical Django Projects by James Bennett. Among other things, it guides you through the development of a web blog with multiple time-based views (by month, etc) that should serve you well as the basis for your application.

By : Ned Deily

One option you can try is to create a custom manager for your model that provides a way to pull out the archives. Here's code that I use:

from django.db import models, connection
import datetime

class EntryManager(models.Manager):
    def get_archives(self, level=0):
        query = """
                        YEAR(`date_posted`) AS `year`,
                        MONTH(`date_posted`) AS `month`,
                        count(*) AS `num_entries`
By : Adam

This video can help you solving your question :)
By: admin