如何从另一个模块扩展模板?

3 投票
1 回答
1402 浏览
提问于 2025-04-20 04:24

我有一个项目,结构如下:

project    
    project
        static/
        templates
            project
                base.html
        __init__.py
        .....
    events
        static/
        templates
            events
                events.html
        __init__.py
        models.py
        .....

问题

我想在 events.html 中扩展 base.html

我尝试了以下方法:

{% extends "project:project/base.html" %}

但是出现了以下错误

Exception Type:     TemplateDoesNotExist
Exception Value:    project:project/base.html

我也尝试了:

{% extends "base.html" %}

但是返回了相同的错误

Exception Type:     TemplateDoesNotExist
Exception Value:    base.html

INSTALLED_APPS 中我有:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'events',
    'project',
)

TEMPLATE_DIRSBASE_DIR

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

TEMPLATE_LOADERS 中我有:

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',

)

1 个回答

1

你的 TEMPLATE_DIR 设置为 project/templates,而不是 project/templates/project

因为在 project/templates 里没有找到 base.html,所以 Django 报错了。

你可以把 base.html 移动到 project/templates 这个文件夹里,或者通过下面的方式来引用它:

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

撰写回答