gpt4 book ai didi

Django 模板扩展了错误的模板

转载 作者:行者123 更新时间:2023-12-02 09:23:57 24 4
gpt4 key购买 nike

我的项目中有多个应用程序:

  • 应用程序1/
    • 模板/
      • base.html
      • some_template.html
  • 应用2/
    • 模板/
      • base.html
      • 概述/
        • index.html

app2/templates/overview.index.html 有以下代码:

{% extends 'base.html' %}

所以它应该扩展app2/templates/base.html

但事实上它扩展了app1/templates/base.html!为什么以及如何解决它?

最佳答案

应用模板加载器返回第一个匹配的模板,它不知道您正在特定应用“内部”渲染模板。

Django docs recommend您将应用的模板放在 myapp/templates/myapp 中,而不是 myapp/templates/ 中。这可以防止模板发生冲突。

Now we might be able to get away with putting our templates directly in polls/templates (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.

因此,在您的情况下,您可以将结构更改为

  • 应用程序1/
    • 模板/
      • 应用程序1/
        • base.html
        • some_template.html
  • 应用2/
    • 模板/
      • 应用2/
        • base.html
        • 概述/
          • index.html

然后,您必须更新 View 中的模板名称,例如

return render(request, 'app2/some_template.html', {})

并在您的模板中

{% extends 'app2/base.html' %}

关于Django 模板扩展了错误的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33829759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com