Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?

后端 未结 4 650
情歌与酒
情歌与酒 2020-12-17 10:27

I would like to globally (through my entire site, admin and front-end) adjust the way dates and time are displayed to my likings, but I cannot figure out what is going on wi

4条回答
  •  盖世英雄少女心
    2020-12-17 10:45

    Had same problem, solution is simple and documented. Whenever you render a date, you need to specify you want the template to render it as a date/time/short_date/datetime (e.g., {{ some_date_var | date }} and then it will render it as specified with DATE_FORMAT in your settings.py

    Example:

    >>> from django.conf import settings  # imported to show my variables in settings.py 
    >>> settings.DATE_FORMAT #  - showing my values; I modified this value
    'm/d/Y'
    >>> settings.TIME_FORMAT
    'P'
    >>> settings.DATETIME_FORMAT
    'N j, Y, P'
    >>> from django.template import Template, Context
    >>> from datetime import datetime
    >>> c = Context(dict(moon = datetime(1969, 7, 20, 20, 17, 39))) # Create context with datetime to render in a template
    >>> print c['moon'] # This is the default format of a printing datetime object 
    1969-07-20 20:17:39
    >>> print Template("default formatting : {{ moon }}\n"
                       "use DATE_FORMAT : {{ moon|date }}\n"
                       "use TIME_FORMAT : {{ moon|time }}\n"
                       "use DATETIME_FORMAT: {{ moon|date:'DATETIME_FORMAT' }}\n"
                       "use SHORT_DATETIME_FORMAT: {{ moon|date:'SHORT_DATETIME_FORMAT' }}"
                       ).render(c)
    default formatting : 1969-07-20 20:17:39
    use DATE_FORMAT : 07/20/1969
    use TIME_FORMAT : 8:17 p.m.
    use DATETIME_FORMAT: July 20, 1969, 8:17 p.m.
    use SHORT_DATETIME_FORMAT: 07/20/1969 8:17 p.m.
    

    This makes sense; e.g., the template needs to know whether it should use the DATE_FORMAT or the SHORT_DATE_FORMAT or whatever.

提交回复
热议问题