如何在Django网站上显示当前日期和时间?

时间:2019-10-17 04:55:51

标签: python html django datetime bootstrap-4

我知道如何在控制台中打印当前日期和时间,但是我正在尝试使用Django和Bootstrap4在我的日常任务Python网站上将日期/时间添加为功能。

我尝试将其作为函数添加到我的views.py文件中,然后将该函数插入到我希望其打开的页面的html文件中,但是我尝试过的所有方法均无效。

这是我最初在views.py中创建的功能:

def today():
    """Shows todays current time and date."""
    today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
    return today

然后我开始玩耍并尝试以下方法:

def today(request):
    """Shows todays current time and date."""
    today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
    context = {'today': today}
    return render(request, context)

这是我尝试添加到html文件中的内容:

<h4>{{ today }}</h4>

更新-尝试执行此操作仍然不显示任何内容:

def today(request):
    """Shows todays current time and date."""
    today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
    context = {'today': today}
    return render(request, 'learning_logs/topics.html', context)

2 个答案:

答案 0 :(得分:1)

如果只想显示在模板中,则可以执行this

Current datetime:{% now "jS F Y H:i" %}

答案 1 :(得分:0)

return render(request, "example.html", context)

在代码模板中缺少名称,这就是为什么函数找不到要呈现的模板的原因