You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django新手求助:模板block标签失效,浏览器渲染原始代码

Django模板block标签失效排查方案

一、修正模板目录结构

你的当前目录结构存在路径错误,导致Django无法正确识别模板继承关系:

.core
---templates
-- core
- base.html
-frontpage.html

frontpage.html应放在templates/core/目录下,正确结构如下:

.core
---templates
----core
------base.html
------frontpage.html

因为视图中调用的是render(request, 'core/frontpage.html'),Django会默认去templates/core/路径下查找模板文件,位置错误会直接导致模板继承失效,原始代码被浏览器直接渲染。

二、验证settings.py模板配置

确保项目配置文件settings.py中以下项配置正确:

  1. INSTALLED_APPS 已添加core应用:
INSTALLED_APPS = [
    # 其他默认应用(如django.contrib.admin等)
    'core',
]
  1. TEMPLATES 开启APP_DIRS并正确指定模板目录:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # 指向项目根目录下的templates文件夹
        'APP_DIRS': True,  # 允许Django自动搜索各应用下的templates目录
        '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',
            ],
        },
    },
]

若APP_DIRS为False,Django无法自动识别应用内的模板目录,会导致模板标签无法被解析。

三、检查模板标签语法规范

  1. frontpage.html中的{% extends 'core/base.html' %}必须是模板的第一行代码,前面不能有任何空格、换行或其他字符,否则模板继承会直接失效。
  2. 确认所有模板标签拼写正确,比如{% block title %}和{% endblock %}没有漏写百分号、花括号,或出现拼写错误。

四、强制刷新浏览器缓存

浏览器可能缓存了未解析的旧页面,按Ctrl+F5强制刷新页面,查看是否正常渲染。

内容的提问来源于stack exchange,提问作者Ash Lyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 20:00:09