首页 > 解决方案 > 如何使用基于类的视图从不同的应用程序在 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 中工作?

如果这是一个太简单的问题,我们深表歉意,并感谢您的帮助。赞赏!

标签: pythondjangodjango-viewsdjango-templates

解决方案


模板位于不同的应用程序中这一事实没有任何区别。搜索模板文件夹。因此,这意味着您可以通过以下方式访问模板:

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/


推荐阅读