首页 > 解决方案 > django 日期时间过滤器在模板中不起作用

问题描述

我无法在模板中过滤 models.DateTimeField(default=timezone.now)

在我的模板中,我使用了 |date:"F d, Y" 来过滤日期。它显示的是原始字符串而不是过滤,但是如果我删除:“F d,Y”那么它正在工作

模型.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

# Create your models here.


class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

模板

{% extends 'blog/base.html' %} {% block content %} {% for post in posts %}
<article class="media content-section">
    <div class="media-body">
        <div class="article-metadata">
            <a class="mr-2" href="#">{{ post.author }}</a>
            <small class="text-muted">{{
                post.date_posted | date: "F d, Y"
            }}</small>
        </div>
        <h2>
            <a class="article-title" href="#">{{ post.title }}</a>
        </h2>
        <p class="article-content">{{ post.content }}</p>
    </div>
</article>
{% endfor %} {% endblock content %}

这可能是什么原因以及如何解决这个问题?

标签: django

解决方案


Django 的模板语言在间距方面有点严格。您不应在大括号 ({{}}) 之间添加新行。此外,您不应在冒号后添加空格date:

{% extends 'blog/base.html' %} {% block content %} {% for post in posts %}
<article class="media content-section">
    <div class="media-body">
        <div class="article-metadata">
            <a class="mr-2" href="#">{{ post.author }}</a>
            <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
        </div>
        <h2>
            <a class="article-title" href="#">{{ post.title }}</a>
        </h2>
        <p class="article-content">{{ post.content }}</p>
    </div>
</article>
{% endfor %} {% endblock content %}

推荐阅读