【问题标题】:Modifying display format of DateTimes in django-tables2修改 django-tables2 中 DateTimes 的显示格式
【发布时间】:2015-03-18 21:32:39
【问题描述】:

我目前正在使用 django-tables2 来显示我的模型的查询集。此模型的属性之一是精确到毫秒的 DateTimeField,它在我的表中被截断为分钟。

我之前用 HTML 手动实现了一个简单的表格,没有任何问题。我的 DateTimeFields 遵循我的设置中应用的 DATETIME_FORMAT:

settings.py

DATETIME_FORMAT = 'Y N j, H:i:s.u'

自从我开始使用 django-tables2 以来,问题就出现了。有什么方法可以修改它显示 DateTimeFields 的方式或使其遵循我指定的 DATETIME_FORMAT?我需要保留排序功能,因此不能转换为字符串。

我正在使用 render_table 来显示我的表格。以下是我的表类:

class ModelTable(tables.Table):
    class Meta:
        model = Measurement
        sequence = ('date_time', 'latitude', 'longitude',
                    'depth', 'soundvel', 'instrument')

【问题讨论】:

    标签: python html django django-tables2


    【解决方案1】:

    问题解决了。

    django-table2 的 DateTimeColumn 类似乎在我的 settings.py 中寻找 SHORT_DATETIME_FORMAT 而不是 DATETIME_FORMAT。更新了我的设置文件中的值,一切正常。

    【讨论】:

      【解决方案2】:

      当我尝试使用 Python 日期时间格式化选项时,这让我困惑了一段时间。 Django 模板的格式化选项适用于 django-tables2,并在 Django 文档中完整列举:
      https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatefilter-date

      因此,如果您有一个包含一个日期时间列的模型,并且您希望将他们的生日格式化为 Month Day Year, Hour:Minute AM/PM,那么您将输入以下内容:

      class MyTable(tables.Table):
          birthday = tables.DateTimeColumn(format ='M d Y, h:i A')
      
          class Meta:
              model = Person
              attrs = {'class': 'table'} 
              fields =  ['birthday']
      

      【讨论】:

        【解决方案3】:

        您可以将“格式”作为参数添加到 DateTimeColumn。

        https://django-tables2.readthedocs.io/en/latest/_modules/django_tables2/columns/datetimecolumn.html

        class DateTimeColumn(TemplateColumn):
            """
            A column that renders `datetime` instances in the local timezone.
        
            Arguments:
                format (str): format string for datetime (optional).
                              Note that *format* uses Django's `date` template tag syntax.
                short (bool): if `format` is not specified, use Django's
                              ``SHORT_DATETIME_FORMAT``, else ``DATETIME_FORMAT``
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-12-23
          • 2021-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多