我是Django的新手,并且跟随本教程学习。我希望这只是一个明显的错误,但是我无法让我的Web浏览器呈现用Django模板语言编写的任何内容,而且我不知道为什么。
这是我在某些情况下的目录结构:https://imgur.com/dGNIiDa
project / urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('budget/', include('budget.urls')),
path('admin/', admin.site.urls)
]
budget / urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('<int:account_id>/', views.get_account, name='detail'),
]
budget / views.py:
from django.shortcuts import render
from django.http import HttpResponse
from budget.models import Account, Transaction
def get_account(request, account_id):
accts = Account.objects.filter(pk=account_id)
context = {"test": accts}
return render(request, 'budget/detail.html', context)
budget / templates / budget / detail.html:
<p>This is a {{ context.test }}</p>
当我在浏览器中访问localhost:8000/budget/1
时,将呈现以下内容:https://imgur.com/j2Vh0yb
很显然,Django正在查找模板文件并将其发送到浏览器,但是{}内编写的任何内容都不会被识别或渲染。我完全按照教程进行操作,但不知道为什么它不起作用。有什么想法吗?
答案 0 :(得分:1)
您无需在模板的表达式中使用context
;您在上下文中输入的所有内容都是模板中的“全局变量”,因此请尝试
<p>This is a {{ test }}</p>
相反。
Django的模板引擎的不幸之处在于,它对不存在的属性保持沉默,因此很难调试此类内容。