python - Django 模板上下文未显示

标签 python django django-templates django-views

嗨,我正在使用模板上下文变量,但无论我做什么,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/

相关文章:

python - 在 python 脚本中嵌入资源

python - 如何在同一文件中编写脚本/库?

python - 无法访问 Django 中的静态文件 - 开发服务器

javascript - 这是否存在 : HTML Template Renderer Written in JavaScript?

django - 提高forms.ValidationError不能在自定义模板形式下工作

python - GTK3:听主题变化

python - 如何将 BytesIO 与 matplotlib 和 pyqt5 一起使用?

python - Django 和单位转换

Django admin查看上传的照片

django - 使用 "i18n_pattern"在 URL 中显示语言前缀后无法设置语言