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

无需搭建完整Django应用,如何渲染含变量的模板?

解决Django模板渲染报错:No DjangoTemplates backend is configured

报错原因是你没有配置Django的模板后端,哪怕不搭建完整项目,也需要做最小化的配置来启用模板引擎。以下是直接渲染模板字符串的可行方案:

方案一:使用Template和Context类

创建一个Python脚本(比如render_template.py),写入以下代码:

import django
from django.conf import settings
from django.template import Template, Context

# 初始化最小化Django配置
if not settings.configured:
    settings.configure(
        INSTALLED_APPS=[
            'django.contrib.contenttypes',
            'django.contrib.auth',
        ],
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'OPTIONS': {
                    'context_processors': [
                        'django.contrib.auth.context_processors.auth',
                    ],
                },
            },
        ]
    )
    django.setup()

# 你的模板内容
template_str = """
<html>
  <body>
    hello <strong>{{username}}</strong>
    your account is activated.
  </body>
</html>
"""

# 渲染模板
template = Template(template_str)
context = Context({'username': '你的用户名'})
result = template.render(context)

print(result)

方案二:通过模板引擎直接渲染

另一种更简洁的写法,同样在脚本中:

import django
from django.conf import settings
from django.template import engines

if not settings.configured:
    settings.configure(
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
            },
        ]
    )
    django.setup()

# 获取Django模板引擎并渲染
engine = engines.get('django')
template = engine.from_string("""
<html>
  <body>
    hello <strong>{{username}}</strong>
    your account is activated.
  </body>
</html>
""")

result = template.render({'username': 'TestUser'})
print(result)

运行步骤

  1. 确保已安装Django:pip install django
  2. 运行脚本:python render_template.py

执行后就能看到替换了username变量的HTML内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:17:17