筛选DateField对象

2024-10-04 05:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这个问题上读过很多类似的Stackoverflows,但是我的问题似乎更具体。我无论如何都无法获取要显示的日期,但默认值是。你知道吗

以下是所讨论的模型:

class Blog (models.Model):
    ...
    posted = models.DateField(db_index=True)

然后像这样传递给模板,作为中包含的对象的一部分Blog.objects.all全部():

def index(request):
    return render_to_response('index.html', {
        'categories': Category.objects.all(),
        'posts': Blog.objects.all()[:10:-1],
    })

因此,目前在我的模板中,我可以通过在模板中写入以下内容来显示日期字段信息,因为posted是对象的一个属性:

{% for post in posts %}
    {{ post.posted }}
{% endfor %}

如果我这样做的话,它会以一种相当难看的方式显示日期:2014-02-24

如何更改此显示?

我已经尝试过的事情:

  • {{ post.posted|date:"D M j Y" }}显示为空
  • {{post.posted|date }}与设置.py包括DATE_FORMAT = 'D M j Y'这也只是显示为空
  • 各种组合的USEL10N = False USEL10N = True。。。仍然只是显示空白

对于1.6的文档来说,使用“| date”过滤器听起来非常简单,但它在我这边不起作用。有什么想法吗?你知道吗

谢谢你。你知道吗


Tags: 对象模型模板truedateindexobjectsmodels
1条回答
网友
1楼 · 发布于 2024-10-04 05:25:11

我现在还不能测试这个,但文件里的东西吸引了我的注意。你知道吗

这个documentation for the date template filter

if value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string 'Wed 09 Jan 2008'.

documentation for the ^{} model field表示该字段包含

a date, represented in Python by a datetime.date instance.

可能是date模板筛选器没有将datetime.date实例作为其参数吗?尝试将Blog模型的posted字段更改为DateTimeField,看看会发生什么。你知道吗

相关问题 更多 >