How do you change the order of Django's SelectDateWidget to day, month, year?

最后都变了- 提交于 2019-12-19 08:21:12

问题


This is the form:

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)

The date of birth field is rendered like so

How do I change it so that it will render as day, month, year?


回答1:


From the source code of this widget I see the the order of dropdowns is defined by DATE_FORMAT setting:

    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)    

Try to change DATE_FORMAT in settings.py to j N, Y for example.




回答2:


If you look in django/forms/extras/widgets.py where SelectDateWidget is defined the render function contains this snippet of code.

 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 uses get_format('DATE_FORMAT')

It looks like DATE_FORMAT can be set in the settings.py

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



来源:https://stackoverflow.com/questions/6136830/how-do-you-change-the-order-of-djangos-selectdatewidget-to-day-month-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!