【问题标题】:How to use custom made django template tags inside django-tables2?如何在 django-tables2 中使用定制的 django 模板标签?
【发布时间】:2015-06-29 03:22:00
【问题描述】:

我在我的项目中实现了 django-tables2 以更快地加载我的数据。我有mytags.py 由许多定制的模板标签组成。有人可以帮助我如何将我的标签实现到我的 html 中吗?以下是我的标签之一的示例,以及在实现 django-tables2 之前我如何在我的 html 中实现。提前致谢。

html:

<td>{{ table.start_time|get_total:table.Date_Time_End|default:"---" }}</td>

标签:

@register.filter
def get_total(date_start=None, date_end=None):
    fmt = '%Y-%m-%d %H:%M:%S'
    if date_start is not None and date_end is not None:
        ds = str(date_start)
        new_ds = ds[:19]
        de = str(date_end)
        new_de = de[:19]
        date_start = datetime.strptime(new_ds, fmt)
        date_end = datetime.strptime(new_de, fmt)
        return date_end - date_start
    else:
        return None

【问题讨论】:

    标签: python html django django-templates django-tables2


    【解决方案1】:

    如果您想在表格中添加其他字段 - 试试这个

    class YourModel(models.Model):
        # here your fields
    
        @property
        def total_date(self):
            fmt = '%Y-%m-%d %H:%M:%S'
            if self.date_start is not None and self.date_end is not None:
                ds = str(self.date_start)
                new_ds = ds[:19]
                de = str(self.date_end)
                new_de = de[:19]
                date_start = datetime.strptime(new_ds, fmt)
                date_end = datetime.strptime(new_de, fmt)
    
                return date_end - date_start
            else:
                return None
    

    然后将其添加到您的表类字段中

    class YourTableClass(tables.Table):
        total_date = tables.Column(verbose_name='Total date')
    
        class Meta:
            model = YourModel
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-20
      • 2014-04-23
      • 2022-11-25
      • 1970-01-01
      • 2011-09-17
      • 2013-10-04
      • 1970-01-01
      • 2020-02-08
      相关资源
      最近更新 更多