How to format DateTimeField in Django Admin to localtime?

前端 未结 1 1678
别那么骄傲
别那么骄傲 2021-02-15 16:51

How to format DateTimeField in Admin according to localtime and timezone ?

My settings.py:

    TIME_ZONE = \'Europe/Bratislava\'
    LANGUAGE_CODE = \'e         


        
相关标签:
1条回答
  • 2021-02-15 17:28

    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

    0 讨论(0)
提交回复
热议问题