【问题标题】:Python - Google App Engine - Methods in Django templatePython - Google App Engine - Django 模板中的方法
【发布时间】:2011-12-19 04:15:50
【问题描述】:

我来自 Rails 编程经验。

我正在使用 Django 模板在 Google App Engine 上使用 Python 编写应用程序。

我不能在日期时间调用 strftime("%I:%M %p")。

在我的 main.py 文件中,我有:

import datetime
....
class Report(db.Model):
    date = db.DateTimeProperty(auto_now_add = True)

我将所有报告传递给模板,并且在我拥有的模板中:

{% for report in reports %}
<tr>
    <td>{{ report.date.strftime("%I:%M %p") }}</td>
</tr>
{% endfor %}

我知道我有一个日期时间对象,因为我可以做到:

{{ report.date.day }} 

或:

{{ report.date.minute }} 

很好,他们会返回他们应该返回的东西。

当我有的时候:

 {{ report.date.strftime("%I:%M %p") }}

我得到错误:

raise TemplateSyntaxError, "Could not parse the remainder: %s" % token[upto:] TemplateSyntaxError: Could not parse the remainder: ("%I:%M %p")

如何让 strftime 工作?

【问题讨论】:

    标签: python google-app-engine methods django-templates


    【解决方案1】:

    Django 模板引擎不支持将参数传递给这样的方法。要完成同样的事情,请尝试使用the date filter

    {{ report.date|date:"f A" }}
    

    (已编辑:修复了日期字符串的语法,因为我很愚蠢。)

    【讨论】:

    • 谢谢!我做了{{ report.date|date:"f A" }}
    【解决方案2】:

    Django 模板系统是“meant to express presentation, not program logic”,这就是为什么它“不是简单地将 Python 嵌入 HTML”。

    默认情况下仅支持标签和过滤器。这就是为什么您需要像@Dougal 那样找到与您指出的功能类似的过滤器。 另一种选择是创建一个custom template tag or filters,但在这种情况下会有点矫枉过正。

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 2011-09-18
      • 2011-06-18
      • 2012-11-17
      • 1970-01-01
      • 2010-10-20
      • 2011-04-22
      • 2011-04-28
      • 2011-08-06
      相关资源
      最近更新 更多