你如何将Django的SelectDateWidget的顺序改为日,月,年?

时间:2011-05-26 10:03:55

标签: django django-forms

这是表格:

from django.forms.extras.widgets import SelectDateWidget


class EntryForm(forms.ModelForm):

    class Meta():
        model = Entry

    def __init__(self, *args, **kwargs):
        super(EntryForm, self).__init__(*args, **kwargs)
        this_year = datetime.date.today().year
        years = range(this_year-100, this_year+1)
        years.reverse()
        self.fields["date_of_birth"].widget = SelectDateWidget(years=years)

出生日期字段如此呈现

enter image description here

如何更改它以使其呈现为日,月,年?

2 个答案:

答案 0 :(得分:6)

从这个小部件的源代码中我看到下拉列表的顺序由DATE_FORMAT设置定义:

    format = get_format('DATE_FORMAT')
    escaped = False
    output = []
    for char in format:
        if escaped:
            escaped = False
        elif char == '\\':
            escaped = True
        elif char in 'Yy':
            output.append(year_html)
        elif char in 'bFMmNn':
            output.append(month_html)
        elif char in 'dj':
            output.append(day_html)    

尝试将settings.py中的DATE_FORMAT更改为j N, Y,例如。

答案 1 :(得分:1)

如果你查看定义了SelectDateWidget的django/forms/extras/widgets.py,渲染函数就会包含这段代码。

 90         output = []
 91         for field in _parse_date_fmt():
 92             if field == 'year':
 93                 output.append(year_html)
 94             elif field == 'month':
 95                 output.append(month_html)
 96             elif field == 'day':
 97                 output.append(day_html)
 98         return mark_safe(u'\n'.join(output))

_parse_date_fmt使用get_format('DATE_FORMAT')

看起来DATE_FORMAT可以在settings.py

中设置

https://docs.djangoproject.com/en/dev/ref/settings/#date-format