【问题标题】:How to render a template in django from a different app using Class Based Views?如何使用基于类的视图从不同的应用程序在 django 中呈现模板?
【发布时间】:2020-07-01 19:52:31
【问题描述】:

我觉得我不应该问这个问题,因为这似乎太容易了。但我在 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

所以我现在可以轻松地在我的 app3 中的template_name 中渲染一个模板,并在那里吐出我所有的项目对象。但我想在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 中工作?

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

【问题讨论】:

  • users/welcome_pages/welcome_user.html 呢?

标签: python django django-views django-templates


【解决方案1】:

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

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 setting [Django-doc]设置为True,它会搜索应用的模板目录,最终在你的users/应用的template/目录下找到users/目录,并找到相关模板。

【讨论】:

  • 我没试过……非常感谢@Willem!救了我:)
猜你喜欢
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
  • 2020-03-12
  • 2012-07-31
相关资源
最近更新 更多