This blog is now hosted at consciou.us

Monday, March 1, 2010

Django Forms: Alternate Date Handling

For usability on the "score" page at Sage Steps (free registration required if you want to check it out), we decided that the best method to present a date was a simple drop-down with, e.g. "February 2010" as the text.

I tried out several permutations with mixed luck, but then happened upon the following recipe:

def month_year():
    today = date.today()
    today = date(today.year, today.month, 1)
    dates = []
    for i in range(1,13):
        if (today.month > i):
            month = today.month - i
            year = today.year
        else:
            month = 12-(i-today.month)
            year = today.year - 1
        mon = date(year, month, 1)
        dates.append((mon, mon.strftime("%B %Y")))
    dates.reverse()
    return dates

This creates a set of tuples, e.g.: (date(2009,3,1), 'March 2009'),

month = DateField(widget=Select(choices=month_year()))

This will produce the drop-down as above, and

form.cleaned_data['month']

Will actually return a datetime.date object (trust me, that's a good thing).

2 comments:

Microsoft Office said...

Microsoft Outlook 2010 to help control email volume, you can find the desired content, and perform operations at the appropriate time and location. Outlook 2010 download needs no introduction since it is the industry standard.

Microsoft Office said...

"Microsoft Microsoft Outlook 2010 Place of work Outlook 2010 Research Folders might keep track of e-mail based on your wants, which can increase the performance involving employment. You possibly can lower the time period spent in this Microsoft Outlook 2010 download therapy for e-mail, the very best, that include a criminal record more time to reply.The investigation file is usually a real-time listings that seem to be and performance including e-mail version, and not a e-mail kept in these people, Download outlook 2010 although has the take a look at this e-mail things that connect with unique investigation conditions. Could "search folders" as being a latest kept look ups, and try to watch all the items in every versions "Search Folders" circumstances - but it surely Outlook 2010 does not project away from the initial directory. Office Professional 2007