Django项目中HTML模板无法渲染,浏览器显示源码问题排查
Django模板渲染异常排查:变量不渲染+浏览器显示HTML源码
以下是针对这类问题的常见排查方向和解决办法:
1. 视图函数未使用正确的模板渲染方法
如果直接用HttpResponse返回模板文件路径或原始模板内容,Django不会解析模板变量和标签,会直接把内容当作纯文本输出到浏览器。
错误示例:
from django.http import HttpResponse def index(request): return HttpResponse("templates/index.html")
正确写法:使用render()函数,它会自动处理模板加载、变量渲染,并返回正确的HTML响应:
from django.shortcuts import render def index(request): context = {"username": "DrewS"} return render(request, "index.html", context)
2. 模板语法错误
变量渲染必须用双大括号{{ 变量名 }},如果语法错误(比如单大括号、拼写错误),浏览器会直接显示这些语法字符而非渲染后的值。
错误示例:
<p>欢迎您,{username}</p>
正确示例:
<p>欢迎您,{{ username }}</p>
另外,模板标签(如{% if %}、{% for %})必须正确闭合,未闭合的标签会导致模板解析失败,直接输出源码。
3. 响应Content-Type未设置为text/html
浏览器需要识别响应为HTML类型才会解析渲染,如果返回的是纯文本类型,会直接显示源码。
- 用
render()函数会自动设置Content-Type: text/html,无需手动处理。 - 如果手动使用
HttpResponse返回模板内容,必须指定content_type:
from django.http import HttpResponse from django.template.loader import get_template def index(request): template = get_template("index.html") context = {"username": "DrewS"} return HttpResponse(template.render(context, request), content_type="text/html")
可以在浏览器开发者工具的「Network」面板中查看请求的响应头,确认Content-Type是否为text/html。
4. 模板加载路径配置错误
确保settings.py中的TEMPLATES配置正确,Django能找到你的模板文件:
# settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / "templates"], # 项目根目录下的templates文件夹 'APP_DIRS': True, # 允许Django自动查找各app下的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', ], }, }, ]
模板文件的存放位置要对应:
- 项目根目录的
templates/下:直接写模板文件名(如index.html) - 某app下的
templates/app_name/下:写app_name/index.html
5. 模板引擎后端不匹配
如果settings.py中配置了Jinja2作为模板后端,却使用Django模板语法(反之亦然),会导致模板无法解析,直接输出源码。确保BACKEND与你使用的模板语法一致:
- Django模板语法对应:
'django.template.backends.django.DjangoTemplates' - Jinja2语法对应:
'django.template.backends.jinja2.Jinja2'
内容的提问来源于stack exchange,提问作者DrewS
相关产品推荐
相关产品推荐

