Making Django forms.DateField show use local date format

前端 未结 4 678
死守一世寂寞
死守一世寂寞 2020-12-29 14:35

I\'m trying to find an easy way to build forms which show dates in the Australian format (dd/mm/yyyy). This was the only way I could find to do it. It seems like there sho

4条回答
  •  梦谈多话
    2020-12-29 14:56

    All of the custom widget stuff can be bypassed.

    Here's an excerpt from django/forms/widgets.py:

    class DateInput(TextInput):
        def __init__(self, attrs=None, format=None):
            super(DateInput, self).__init__(attrs)
            if format:
                self.format = format
                self.manual_format = True
            else:
                self.format = formats.get_format('DATE_INPUT_FORMATS')[0]
                self.manual_format = False
    

    You'll notice that the format of the widget is set using the format module. The format module is selected depending on the locale. If you're browsing from the US, Django will, by default, select django.conf.formats.locale.en.formats.py. Here you will find the default format:

    DATE_INPUT_FORMATS = (
        '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
        # '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
        # '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
        # '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
        # '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'
    )
    

    As you can see in the first code block, Django selects the first of these. The thorough approach to changing the format is to create your own format module, overriding Django's default for the locale in question. For that, look into FORMAT_MODULE_PATH. If all you're trying to do is override the default date format, I say save yourself some time and monkey patch. I added this to my settings file and everything appears to be working splendidly with my preferred default format:

    DATE_INPUT_FORMATS = ('%m/%d/%Y', '%m/%d/%y', '%Y-%m-%d',
                          '%b %d %Y', '%b %d, %Y', '%d %b %Y',
                          '%d %b, %Y', '%B %d %Y', '%B %d, %Y',
                          '%d %B %Y', '%d %B, %Y')
    from django.conf.locale.en import formats
    formats.DATE_INPUT_FORMATS = DATE_INPUT_FORMATS
    

提交回复
热议问题