是否可以在 {%extends%} 中仅指定 "base.html" 文件的名称,而不是 "app/base.html"?

Is it possible to only specify the name of the "base.html" file in the {%extends%}, instead of "app/base.html"?

我正在学习 Django,我偶然发现了一个问题: 是否可以在 {% extends "app/base.html" %} 中创建 base.html 文件的路径 link 来自 helloworld.html 文件越短越好? 所以我只需要写 {% extends "base.html" %} 让它工作。

现在,如果我尝试这样做,python 将在 def helloworld(request): 函数中抛出异常 views.py.

所以我的应用程序文件结构是:

├── app
│   ├── migrations
│   ├── static
│   ├── templates 
│      ├── app
│         ├── base.html
│         ├── helloworld.html
│   ├── views.py 
│   └── models.py 
├── DjangoProject
│   ├── __init__.py 
│   ├── urls.py 
│   ├── settings.py 
│   ├── templates 
├── manage.py

helloworld.html:

{% extends "app/base.html" %}

{% block head_title %} hello {% endblock %}

{% block content %} 
<p> hello world </p> 
{% endblock %}

views.py:

from django.shortcuts import render
from django.http import HttpRequest

def helloworld(request):
    hello_title = 'Test'
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/helloworld.html',
        {
            'title_test':hello_title    
        }
    )

settings.py:

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
    'app',]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates'),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

我已经尝试在 'DIRS:' 部分的 TEMPLATES 部分包含另一条路径 settings.py 文件,但它似乎不起作用。 我发现 django 文档和另一个 Whosebug post 只谈论添加“app/base.html”路径。

当然,您可以通过简单地使用 {% extends template_name %}

从您的视图发送它

在您看来:

return render(
    request,
    'app/helloworld.html',
    {
        'title_test': hello_title,
        'template_name': 'app/base.html'
    }
)

请记住,这不会使用您在渲染中提供的标题。 要使用标题,它需要在模板中有一个具有该名称的变量。
{% block head_title %} {{ title_test }} {% endblock %}

就我个人而言,我的做法是将应用程序名称放在不同的变量中,例如:

class MyView(View):
    template_name = f'{APP_NAME}/{TEMPLATE_NAME}'
    ...
    def get(self, request, *args, **kwargs)
        return render(
            request,
            'app/helloworld.html',
            {
                'title_test': hello_title,
                'template_name': self.template_name
            }
        )

两个变量都是我从不同文件导入的常量。