0

私のブログアプリでは、現在の月までの5か月連続の月番号と対応する年を格納する構造(コンテキストプロセッサで変数として作成された)が必要です。したがって、現在の月が12月の場合、年は2010年、月は12、11、10、9、8になります。月が1月の場合、2010年:月:1および年:2009月:12、11、10、9になります。私の目標は、次の形式でアーカイブを表示することです。

- 2010
    - January
- 2009
    - December
    - November
    - October
    - September

それを作成する方法とどのような構造を使用する必要がありますか?そして、それをどのように表示するのですか?ネストされた構造が必要だと思いますが、django <1.2でレンダリングすることは可能ですか?
私は自分でそれを始めましたが、ある時点で完全に失われました:

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]
4

1 に答える 1

2

それを作成する方法とどのような構造を使用する必要がありますか?

年月のタプルのリストを使用します。これがサンプル実装です。これを機能させるには、便利なpython-dateutilライブラリが必要です。

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())

そして、それをどのように表示するのですか?

これは、それを表示するための非常に単純な方法です。<ul>要素を置き換え<div>て適切にスタイリングすることで、クリーンアップできると思います。

    <ul>
    {% for year, month in previous_year_months %}
        {% ifchanged year %}
            </ul><li>{{ year }}</li><ul>
        {% endifchanged %}
                <li>{{ month }}</li>
    {% endfor %}
    </ul>

ここprevious_year_monthsで、はによって返される結果に対応するコンテキスト変数ですget_current_and_5_previous_months

于 2010-10-04T06:16:37.313 に答える