from datetime import datetime
from dateutil.relativedelta import relativedelta
def get_blog_archive(request):
now = datetime.today()
first_month = datetime(now.year, now.month, 1)
previous_months = (first_month - relativedelta(months = months) for months in range(0, 5, 1))
news_archive = {}
for pm in previous_months:
m = translate_month(pm.month)
if news_archive.has_key(pm.year):
news_archive[pm.year].append(m)
else:
news_archive[pm.year] = [m]
m = translate_month(current_month)
news_archive[current_year].append(m)
return {'NEWS_ARCHIVE': news_archive,}
def translate_month(month):
ret_month = ""
months = {
1: "Styczeń",
2: "Luty",
3: "Marzec",
4: "Kwiecień",
5: "Maj",
6: "Czerwiec",
7: "Lipiec",
8: "Sierpień",
9: "Wrzesień",
10: "Październik",
11: "Listopad",
12: "Grudzień",
}
ret_month = months.get(month)
return ret_month
Okay this code is nice but not really functional, beacuse we get months names as String (here with utf-8 chars) and its troublesome to parse them as urls. So here's a bit more functional approach :
news_archive = []
for pm in previous_months:
d = datetime(pm.year,pm.month,1)
news_archive.append(d)
return {'NEWS_ARCHIVE': news_archive,}
And now in our template we just parse with for loop through list elements.
So that's all and stay tooned for some more advanced django examples. I'm doing a really big project right now but there's a ready shoutbox for django example, few implementations of django-registration, something about handling files and more :)
No comments:
Post a Comment