嗨,我正在使用模板上下文变量,但无论我做什么,current_datetime View 函数的上下文都不会显示在 home.html 中,并且没有错误消息...我做错了什么?
#######view.py
def current_datetime(request):
now = datetime.datetime.now()
context = {
"current_date": now
}
return render(request, "current_datetime.html",context)
def home(request):
title = "My Database"
context = {
"template_title": title,
}
return render(request,"home.html",context)
#######current_datetime.html
Today is {{ current_date }}
#######home.html
{% extends "base.html" %}
....
{% include 'current_datetime.html' %}
....
最佳答案
它不起作用,因为 current_date
变量不在 home
View 的上下文中。
干
不要重复自己。您尝试在模板中显示日期的方式,您必须将该变量传递给每个 View 的上下文,这完全违背了 DRY 原则。
使用{% now %}
标签
不要将当前日期作为上下文变量发送,而是使用名为 {% now %}
的模板标记,该标记在模板中显示日期和时间。这是一个例子:
current_date.html
Today is {% now "jS F Y H:i" %}
将输出:
Today is is 3rd September 2015 08:28
这里有更多关于 formatting the output of now
tag 的信息
关于python - Django 模板上下文未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32367268/