La creazione e il rendering struttura dotata di anni e mesi in Django
-
27-09-2019 - |
Domanda
Nella mia app blogging ho bisogno di una struttura (creata come una variabile in processor contesto) che memorizzerà mesi numero e l'anno corrispondente di 5 mesi consecutivi fino a quella attuale. Quindi, se il mese corrente è Dicembre, avremo anno: 2010 e mesi: 12,11,10,9,8. Se mese sarà gennaio avremo anni 2010: mesi: 1 e anni: 2009 mesi: 12, 11, 10, 9. Il mio obiettivo è quello di mostrare un archivio nella forma seguente:
- 2010
- January
- 2009
- December
- November
- October
- September
Come creare e quale struttura dovrei usare? E poi come mostrarlo? Credo di aver bisogno di un po struttura annidata, ma che sarà possibile rendere in Django <1.2?
Ho iniziato per conto mio, ma ho completamente perso a un certo punto:
now = datetime.datetime.now()
years = []
months = []
archive = []
if now.month in range(5, 12, 1):
months = range(now.month, now.month-5, -1)
if months:
years = now.year
else:
diff = 5 - now.month
for i in range(1, now.month, 1):
archive.append({
"month": i,
"year": now.year,
})
for i in range(0, diff, 1):
tmpMonth = 12 - int(i)
archive.append({
"month": tmpMonth,
"year": now.year-1,
})
if archive:
years = [now.year, now.year-1]
Soluzione
Come creare e quale struttura devo usare?
mi piacerebbe andare con un elenco di anno-mese tuple. Ecco un esempio di implementazione. Avrete bisogno a portata di mano il python-dateutil biblioteca per fare questo lavoro.
from datetime import datetime
from dateutil.relativedelta import relativedelta
def get_5_previous_year_months(a_day):
"""Returns a list of year, month tuples for the current and previous
5 months relative to a_day"""
current_year, current_month = a_day.year, a_day.month
first_of_month = datetime(current_year, current_month, 1)
previous_months = (first_of_month - relativedelta(months = months)
for months in range(0, 5))
return ((pm.year, pm.month) for pm in previous_months)
def get_current_and_5_previous_months():
return get_5_previous_year_months(datetime.today())
E poi come vederlo?
Ecco un modo molto semplicistico di mostrarlo. Penso che si possa ripulire sostituendo gli elementi <ul>
con <div>
e styling in modo appropriato.
<ul>
{% for year, month in previous_year_months %}
{% ifchanged year %}
</ul><li>{{ year }}</li><ul>
{% endifchanged %}
<li>{{ month }}</li>
{% endfor %}
</ul>
Dove previous_year_months
è una variabile contesto corrispondente al risultato restituito da get_current_and_5_previous_months
.