Задать вопрос

Тел: +7 965 3737 888

574

Просмотров

3

Ответов

Month / Year dropdown widget

<p>This is an adaption of </p>
<p><a href="http://code.djangoproject.com/browser/django/trunk/django/forms/extras/widgets.py#L16">django.forms.extras.widgets.SelectDateWidget</a></p>
<p>which has no day dropdown - it still produces a date but with the day set to 1.</p>
<p>Example use</p>
class myForm(forms.Form):
    # ...
    date = forms.DateField(
        required=False,
        widget=MonthYearWidget(years=xrange(2004,2010))
    )

Вопрос полезен? Да0/Нет0
file_4360.py(2.7Кб)
None

Ответы (3):

Ответdanny_adair:19.02.2013
Ответ полезен? Да0/Нет0

"That's why I'm using time.strptime()" - uhm, make that "date.strftime()" :-)

Ответdanny_adair:19.02.2013
Ответ полезен? Да0/Нет0

The second last line

    return '%s-%s-%s' % (y, m, 1)

will only work if you didn't customize your DATE_FORMAT/DATE_INPUT_FORMATS (the former is usually the first item of the latter, i.e. the "preferred" input format). In order for this to always work, add

    from django.conf import settings

at the top, and replace that second last line with:

    return datetime.date(int(y), int(m), 1).strftime(
        settings.DATE_INPUT_FORMATS[0]
    )

P.S.: django.utils.formats.localize() is for rendering output, not input, and expects a setting in the format of DATE_FORMAT, i.e. without percentage signs... That's why I'm using time.strptime()

P.P.S.: Theoretically, the int() conversion could be try'd but the widget doesn't allow free text input so I find it ok to leave it out

Ответleosh:16.02.2011
Ответ полезен? Да0/Нет0

There's a bug in this snippet. Line 56 should read:

    if not (self.required and month_val):

And line 65 should read:

    if not (self.required and year_val):

Otherwise you get strange behavior when only one of them is filled in.