【问题标题】:django form: error message with aware datetimedjango 表单:带有感知日期时间的错误消息
【发布时间】:2019-01-29 14:05:32
【问题描述】:

我正在尝试在我的表单错误消息中添加一个日期时间。不幸的是,它以 UTC(我的 TIME_ZONE)呈现,但应该在当前时区。

def clean(self):
    # print(get_current_timezone()) > Europe/Berlin
    cleaned_data = super(LegForm, self).clean()
    departure_scheduled = cleaned_data.get('departure_scheduled')
    # check departure in journey
    if departure_scheduled < self.instance.journey.start:
        journey_start = localize(self.instance.journey.start)
        # print(self.instance.journey.start.tzinfo) > UTC
        self.add_error(
            'departure_scheduled',
            _('Error Message (%(start)s).') % {'start': journey_start}
        )

print(get_current_timezone()) 返回Europe/Berlin

print(self.instance.journey.start.tzinfo) 返回UTC

当前时区已激活。是否有任何等于localize() 将日期时间对象转换为当前时区?

【问题讨论】:

  • 使用localtime()
  • 这就是我要找的。​​span>

标签: django validation datetime django-forms django-timezone


【解决方案1】:

我可以使用:

journey_start = localize(self.instance.journey.start.astimezone(get_current_timezone()))

但这感觉就像与 django 的时区支持作斗争。

更新

感谢 Kevin Christopher Henry 的评论,这是我正在寻找的 django 工具:

from django.utils import timezone
journey_start = timezone.localtime(self.instance.journey.start)

https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#usage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2015-09-27
    • 2014-02-07
    • 2017-06-26
    相关资源
    最近更新 更多