Django中get_context_data()方法添加的上下文键值对无法在模板中渲染的问题求助
Django中get_context_data()方法添加的上下文键值对无法在模板中渲染的问题求助
我跟着教程学习Django,之前的内容都运行正常,但现在遇到一个问题:我在views.py里尝试用get_context_data()方法给类视图添加新的上下文键值对,但这些数据无法在HTML模板中渲染出来。以下是我目前的代码和情况:
views.py 代码
from django.shortcuts import render from django.views.generic import TemplateView # Create your views here. def home_page_view(request): context = { "inventory_list": ["Widget 1", "Widget 2", "Widget 3"], "greeting": "THanK yOu foR viSitiNG!", } return render(request, "home.html", context) class AboutPageView(TemplateView): template_name = "about.html" def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context["contact_address"] = "123 Jones Street" context["phone_number"] = "01234 678910" return context
about.html 模板代码
<h1>Company About Page</h1> <p>The company address is {{contact_address}}.</p> <p>The company phone number is {{phone_number}}.</p>
urls.py 代码
from django.urls import path from .views import home_page_view, AboutPageView urlpatterns = [ path("about/", AboutPageView.as_view()), path("", home_page_view) ]
当我启动开发服务器访问about页面时,模板中的{{contact_address}}和{{phone_number}}并没有被替换成我设置的具体值,页面输出效果如下:

我已经反复核对了教程的示例代码,没发现拼写错误;也在网上找过解决方案,但很多内容都是针对超出我当前初学者水平的场景。我接触Django才一周,应该是漏掉了某个很基础的点?
我的运行环境是:Django 5.0.13 + Python 3.12.1,操作系统为Windows 11。
提前感谢大家的帮助!
备注:内容来源于stack exchange,提问作者green_ruby
相关产品推荐
相关产品推荐

