Python 如何使用基于类的视图从不同的应用程序在django中呈现模板?
我觉得我不应该问这个问题,因为它看起来太容易了。但我在django文档或这里找不到解决方案 我想在基于类的通用ListView中呈现一个模板,它位于另一个应用程序的templates文件夹中 我的文件夹结构:Python 如何使用基于类的视图从不同的应用程序在django中呈现模板?,python,django,django-views,django-templates,Python,Django,Django Views,Django Templates,我觉得我不应该问这个问题,因为它看起来太容易了。但我在django文档或这里找不到解决方案 我想在基于类的通用ListView中呈现一个模板,它位于另一个应用程序的templates文件夹中 我的文件夹结构: my_website -app1 -app2 -mywebsite -templates -users -welcome_pages -welcome_user.html -app
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\u name
中渲染模板,并在那里吐出我的所有项目对象。但是我想在welcome_user.html中呈现上下文
通常文档会说我应该使用appname/templatename
,但是我得到了一个TemplateDoesntExist异常。我尝试传递到模板名称:
mywebsite/welcome_user.html
mywebsite/users/welcome_pages/welcome_user.html
welcome_user.html
mywebsite/templates/users/welcome_pages/welcome_user.html
如果我打印出self.get\u template\u 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
class VisualizationView(StaffRequiredMixin,ListView):
模板名称='users/welcome\u pages/welcome\u user.html'
模型=项目
def获取上下文数据(自身,**kwargs):
打印(self.get\u模板\u名称())
context=super(VisualizationView,self)。获取上下文数据(**kwargs)
上下文['projects']=Project.objects.all()
返回上下文
如果您已将设置为
True
,它将搜索应用程序的模板目录,并最终在您的用户/
应用程序的模板/
目录中找到用户/
目录,然后找到相关的模板。关于users/welcome\u pages/welcome\u user.html呢?
?如果我没有尝试过。。。。非常感谢@Willem!救了我:)