Django:在settings.py中使用DATE_FORMAT、DATETIME_FORMAT、TIME_FORMAT?

发布于 2024-09-17 04:52:53 字数 881 浏览 5 评论 0 原文

我想在全球范围内(通过我的整个网站、管理和前端)调整日期和时间的显示方式以满足我的喜好,但我无法弄清楚 中的 DATE_FORMAT、DATETIME_FORMAT 和 TIME_FORMAT 变量发生了什么设置.py

这个问题中,它说设置被忽略。不过这个问题已经一年多了。在 Django 文档中,它说当你有 USE_L10N = True 并且显然 Django 1.2 中发生了一些变化。根据 但这可能存在错误。

我目前使用的是 Django 1.2,当我使用 USE_L10N = True 时,它只会忽略 settings.py 中的日期(时间)格式。当我有 USE_L10N = False 时,它​​似乎也忽略了它们。

有没有办法全局自定义日期和时间显示?或者我应该像 Karen 在 Django 用户 Google 群组帖子中建议的那样创建自己的自定义格式文件?

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 with the DATE_FORMAT, DATETIME_FORMAT and TIME_FORMAT variables in settings.py.

In this question it says that the settings are ignored. The question is over a year old though. In the Django documentation it says they can be used when you have USE_L10N = True and apparently something changed in Django 1.2. According to this however there might be a bug.

I am currently using Django 1.2 and when I have USE_L10N = True it just ignores the date(time) format in settings.py. When I have USE_L10N = False it also seems to ignore them.

Is there a way to globally customize the date and time display? Or should I create my own custom formats file as Karen suggests in the Django Users Google Group post?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

迷迭香的记忆 2024-09-24 04:52:57

回复晚了,但希望这能帮助其他搜索此内容的人。
通过在设置中设置 USE_L10N = True,Django 会查找特定于区域设置的格式,使它们优先于非区域设置相关的设置。

解决方案:(在日期字段上显示 30/12/2017)

from django.conf.locale.en import formats as en_formats

en_formats.DATE_FORMAT = "%d/%m/%Y"

和输入(接受 30/12/2017 或 30-12-2017)

en_formats.DATE_INPUT_FORMATS = ['%d/%m/%Y', '%d-%m-%Y']

参考:https://mounirmesselmeni.github.io/2014/11/06/date-format -in-django-admin/

*在 Django==1.10.7 上测试

A late response, but hopefully this will help anyone else searching for this.
By setting USE_L10N = True in your settings, Django looks for locale specific formats, giving them precedence over non-locale related settings.

The solution: (to display 30/12/2017 on a DateField)

from django.conf.locale.en import formats as en_formats

en_formats.DATE_FORMAT = "%d/%m/%Y"

and for inputs (to accept 30/12/2017 or 30-12-2017)

en_formats.DATE_INPUT_FORMATS = ['%d/%m/%Y', '%d-%m-%Y']

Reference: https://mounirmesselmeni.github.io/2014/11/06/date-format-in-django-admin/

*tested on Django==1.10.7

冰雪梦之恋 2024-09-24 04:52:57

根据我对 Django 4.2.1 的实验,您可以部分格式化日期和时间,但不能完全在 Django 项目中格式化。

在 Django Admin 中,将 DATE_INPUT_FORMATS 设置为格式 < a href="https://docs.djangoproject.com/en/4.2/ref/models/fields/#datetimefield" rel="nofollow noreferrer">DateTimeField() 和 DateField() 并设置 TIME_INPUT_FORMATS 用于格式化 DateTimeField()TimeField()settings.py 中。 *DATETIME_INPUT_FORMATS 不适用于任何部分Django 项目的,您可以看到 我的问题解释了这 3 个设置。

在 Django 模板中,设置 DATETIME_FORMATDATE_FORMATTIME_FORMAT 格式化 DateTimeField()DateField()TimeField() 分别在 settings.py 中,您可以看到 我的问题解释了这 3 个设置以及其他 2 个设置。

*您需要设置 USE_L10N False< /code> 在 settings.py 中使上述设置起作用,因为 USE_L10N 位于它们之前。

You can partially format date and time but not entirely in a Django project according to my experiments with Django 4.2.1.

In Django Admin, set DATE_INPUT_FORMATS to format DateTimeField() and DateField() and set TIME_INPUT_FORMATS to format DateTimeField() and TimeField() in settings.py. *DATETIME_INPUT_FORMATS doesn't work to any parts of a Django project and you can see my question explaining these 3 settings.

In Django Templates, set DATETIME_FORMAT, DATE_FORMAT and TIME_FORMAT to format DateTimeField(), DateField() and TimeField() respectively in settings.py and you can see my question explaining these 3 settings in addition to other 2 settings.

*You need to set USE_L10N False in settings.py to make these settings above work because USE_L10N is prior to them.

浪推晚风 2024-09-24 04:52:56

搜索源码发现DATETIME_FORMAT等仅在调用django.utils.formats.localize()时使用,并且似乎仅在django.template.VariableNode时调用 被渲染。

我不确定模板渲染中具体何时使用 VariableNode,但我猜测如果您打开了 settings.USE_L10N 并且您有一个 VariableNode ,它将被本地化。

localize 看起来像这样:

def localize(value):
    """
    Checks if value is a localizable type (date, number...) and returns it
    formatted as a string using current locale format
    """
    if settings.USE_L10N:
        if isinstance(value, (decimal.Decimal, float, int)):
            return number_format(value)
        elif isinstance(value, datetime.datetime):
            return date_format(value, 'DATETIME_FORMAT')
        elif isinstance(value, datetime.date):
            return date_format(value)
        elif isinstance(value, datetime.time):
            return time_format(value, 'TIME_FORMAT')
    return value

为了回答您的问题,我可能会编写一个快速上下文处理器,对上下文中的所有内容调用 localize()

Searching through the source shows that DATETIME_FORMAT, etc., are only used when django.utils.formats.localize() is called, and that only seems to be called when django.template.VariableNodes are rendered.

I'm not sure when exactly VariableNodes are used in template rendering, but I would guess that if you have settings.USE_L10N turned on and you have a VariableNode, it will be localized.

localize looks like this:

def localize(value):
    """
    Checks if value is a localizable type (date, number...) and returns it
    formatted as a string using current locale format
    """
    if settings.USE_L10N:
        if isinstance(value, (decimal.Decimal, float, int)):
            return number_format(value)
        elif isinstance(value, datetime.datetime):
            return date_format(value, 'DATETIME_FORMAT')
        elif isinstance(value, datetime.date):
            return date_format(value)
        elif isinstance(value, datetime.time):
            return time_format(value, 'TIME_FORMAT')
    return value

To answer your question, I'd probably write a quick context processor that called localize() on everything in the context.

小矜持 2024-09-24 04:52:56

USE_L10N = True 时,您可以通过 DATE_FORMAT、DATETIME_FORMATTIME_FORMAT 和其他日期/时间格式="https://docs.djangoproject.com/en/2.0/topics/i18n/formatting/#creating-custom-format-files" rel="noreferrer">按照 Django 文档中的描述创建自定义格式文件

总之:

  1. settings.py 中设置 FORMAT_MODULE_PATH = 'yourproject.formats'
  2. 创建目录结构 yourproject/formats/en (替换 en 与相应的 ISO 639-1 语言环境代码(如果您使用的是英语以外的其他语言环境),并将 __init__.py 文件添加到所有目录以使其成为有效的 Python 模块
  3. 添加 格式.py 到叶目录,包含要覆盖的格式定义,例如 DATE_FORMAT = 'j. F Y'。

来自实际项目的示例此处

You can override DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT and other date/time formats when USE_L10N = True by creating custom format files as described in Django documentation.

In summary:

  1. Set FORMAT_MODULE_PATH = 'yourproject.formats' in settings.py
  2. Create directory structure yourproject/formats/en (replacing en with the corresponding ISO 639-1 locale code if you are using other locale than English) and add __init__.py files to all directories to make it a valid Python module
  3. Add formats.py to the leaf directory, containing the format definitions you want to override, e.g. DATE_FORMAT = 'j. F Y'.

Example from an actual project here.

樱娆 2024-09-24 04:52:55

有同样的问题,解决方案是简单且有记录。每当您呈现日期时,您需要指定您希望模板将其呈现为日期/时间/短日期/日期时间(例如,{{ some_date_var | date }},然后它将呈现为在 settings.py 中用 DATE_FORMAT 指定 示例

>>> 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.

这是有道理的;例如,模板需要知道是否应该使用 DATE_FORMAT 还是 SHORT_DATE_FORMAT 或其他什么。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文