How to format DateTimeField in Django Admin to localtime?

这一生的挚爱 提交于 2019-12-03 13:24:08

The answer to you question is proper configuration of settings and formats in Django project. Structure of example project:

.
|-- README.md
|-- demo.db
|-- demo_time_set
|   |-- __init__.py
|   |-- demo.db
|   |-- formats
|   |   |-- __init__.py
|   |   `-- en
|   |       |-- __init__.py
|   |       `-- formats.py
|   |-- settings.py
|   |-- urls.py
|   `-- wsgi.py
|-- manage.py
|-- requirments.txt
`-- some_app
    |-- __init__.py
    |-- admin.py
    `-- models.py

You can define it for multiple languages just by providing directory with appropriate name and formats.py inside. The example content of formats.py where all the MAGIC happens can look as follows:

# HERE FORMATING AS shown in:
# LIST: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'd-m-Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'F j'
SHORT_DATE_FORMAT = 'm/d/Y'
SHORT_DATETIME_FORMAT = 'm/d/Y P'
FIRST_DAY_OF_WEEK = 1

# BUT here use the Python strftime format syntax,
# LIST: http://docs.python.org/library/datetime.html#strftime-strptime-behavior

DATE_INPUT_FORMATS = (
    '%d-%m-%Y',     # '21-03-2014'
)
TIME_INPUT_FORMATS = (
    '%H:%M:%S',     # '17:59:59'
    '%H:%M',        # '17:59'
)
DATETIME_INPUT_FORMATS = (
    '%d-%m-%Y %H:%M',     # '21-03-2014 17:59'
)

DECIMAL_SEPARATOR = u'.'
THOUSAND_SEPARATOR = u','
NUMBER_GROUPING = 3

Please notice two links in the comments, which will guide you to lists of proper configurations, which ARE DIFFERENT for DIFFERENT parts!

In your settings.py just add:

FORMAT_MODULE_PATH = 'demo_time_set.formats'

[GITHUB] Here is a full working example: https://github.com/andilab/demo_time_set

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