【问题标题】:django datetime filter not working in templatedjango 日期时间过滤器在模板中不起作用
【发布时间】:2020-03-07 08:58:04
【问题描述】:

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

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

models.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 %}

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

【问题讨论】:

  • 你不应该在管道字符周围添加空格,所以它应该是{{ post.date_posted|date:"F d, Y" }}

标签: django


【解决方案1】:

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 %}

【讨论】:

    猜你喜欢
    • 2015-06-18
    • 2014-09-28
    • 2023-03-07
    • 2021-07-03
    • 2018-05-04
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多