python - 如何使用基于类的视图从不同的应用程序在 django 中呈现模板?
问题描述
我觉得我不应该问这个问题,因为这似乎太容易了。但我在 django 文档或此处找不到解决方案。
我想在基于类的通用 ListView 中呈现模板,该模板位于不同应用程序的模板文件夹中。
我的文件夹结构:
my_website
-app1
-app2
-mywebsite
-templates
-users
-welcome_pages
-welcome_user.html
-app3
-templates
-mytemplate.html
-mytemplate2.html
-views.py
-models.py
在我的 app3 中,我的视图如下所示:
class VisualizationView(StaffRequiredMixin, ListView):
template_name = ????
model = Project
def get_context_data(self, **kwargs):
print(self.get_template_names())
context = super(VisualizationView, self).get_context_data(**kwargs)
context['projects'] = Project.objects.all()
return context
所以我现在可以轻松地渲染一个模板,template_name
该模板位于我的 app3 中,并在那里吐出我所有的项目对象。但我想在welcome_user.html 中呈现上下文。
通常文档说我应该使用appname/templatename
,但我得到一个 TemplateDoesntExist 异常。我尝试传递给 template_name:
mywebsite/welcome_user.html
mywebsite/users/welcome_pages/welcome_user.html
welcome_user.html
mywebsite/templates/users/welcome_pages/welcome_user.html
如果我打印出来,self.get_template_names()
我只会得到 app3 中的模板列表。我以为 django 会自动在整个项目中查找模板文件夹所在的位置?我在这里想念什么?或者这不应该在 CBV 中工作?
如果这是一个太简单的问题,我们深表歉意,并感谢您的帮助。赞赏!
解决方案
模板位于不同的应用程序中这一事实没有任何区别。搜索模板文件夹。因此,这意味着您可以通过以下方式访问模板:
class VisualizationView(StaffRequiredMixin, ListView):
template_name = 'users/welcome_pages/welcome_user.html'
model = Project
def get_context_data(self, **kwargs):
print(self.get_template_names())
context = super(VisualizationView, self).get_context_data(**kwargs)
context['projects'] = Project.objects.all()
return context
如果您将APP_DIRS
设置[Django-doc]设置为True
,它会搜索应用程序的模板目录,最终在您的应用程序users/
目录中找到一个目录,并找到相关的模板。template/
users/
推荐阅读
- c - realloc 如何管理指针大小?
- google-chrome - 运行 audiocapture 代码时 Chrome 无法检测到捕获设备
- c - C定义第一次不使用时扩展不一样的宏
- c - 通过引用错误传递结构(不完整的结构和重新声明)
- java - 如何按时间戳属性过滤对象数组(通过 - 命令替代 SQL 滞后于分区的代码)
- elasticsearch - 如何在多索引搜索中通过索引获取聚合聚合?
- python - 使用 tensorflow-distributed 实现 mask-r-cnn
- c# - 当列表视图中的项目很少时,标题列的右下角是什么?
- firebase - 使用 API 查询 Firebase A/B 测试
- java - 如何在 HashMap 中获取已排序的数组列表?