django - 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 的模板语言在间距方面有点严格。您不应在大括号 ({{
和}}
) 之间添加新行。此外,您不应在冒号后添加空格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 %}
推荐阅读
- sql - 我想使用 DATEDIFF 将两个日期之间的差异转换为整数
- angular - 如何过滤 FormGroup 值?
- vtk - VTK:无法使用多线程渲染窗口
- sass - Angular - 显示字体真棒微调中心不起作用
- r - 如何在 R 中使用 TableGrob 以双向表格图形方式突出显示条件值?
- kotlin - ViewPager2 和 FragmentStatePagerAdapter
- typescript - Typescript 不会在扩展接口中推断值的类型
- python - 什么错误“没有显示名称和没有 $DISPLAY 环境变量”
- c++ - 如果只有一个线程修改了 std::vector,那么同一个线程在从向量读取时是否需要使用锁?
- asp.net - 如何在 Asp.net Core 2 中进行甜甜圈缓存?