【问题标题】:Django template context not showingDjango模板上下文未显示
【发布时间】:2015-09-03 04:57:55
【问题描述】:

您好,我正在使用模板上下文变量,但无论我做什么,来自 current_datetime 视图函数的上下文都不会显示在 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' %}

....

【问题讨论】:

  • 您访问的是什么网址?与 home 相关的还是与 current_datetime 相关的?
  • home...默认的html..
  • default.html 到底是什么意思?问题是“你的网址是什么”?
  • urls 路由到您的视图。将 current_date 添加到上下文的视图不是主视图,而是另一个视图。
  • 是的,我知道,但我使用包含标签 {% include 'current_datetime.html' %}... 这不应该包含在我的 home.html 中吗?

标签: python django django-templates django-views


【解决方案1】:

它不起作用,因为currenct_date 变量不在home 视图的上下文中。

干燥

不要重复自己。您尝试在模板中显示日期的方式,您必须将该变量传递给每个视图的上下文,这完全违反了 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

【讨论】:

  • 如果我访问 current_date.html ,它会显示日期,这很好。但是,如果您查看 home.html,我有包含标签 {% include 'current_datetime.html %}.. 那么当我访问 home.html 时,它不应该也出现吗?日期时间只是一个例子......如果我将它用于其他视图功能怎么办?
  • 如果您在 current_date.html 模板中使用{% now %} 标签,它也会出现在home.html 中。但是,如果您使用上下文变量显示日期,则它不会显示在 home.html 中,除非 home 视图的上下文中有 current_date 变量。
  • 谢谢,这行得通。但这并不是我真正想做的。我只是以日期时间为例。有没有办法让我在一个页面中显示 2 个视图功能?编辑:nvm,我做了一些搜索,显然这是不可能的。谢谢!
猜你喜欢
  • 2016-09-22
  • 1970-01-01
  • 2021-04-21
  • 2020-06-04
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 2012-05-24
  • 1970-01-01
相关资源
最近更新 更多