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

Django服务器运行HTML文件时持续报错TypeError: Invalid path type: module

解决Django中「TypeError: Invalid path type: module」错误

可能的原因及解决步骤:

  • 检查视图中返回模板的代码
    大概率是视图函数里返回render或TemplateResponse时,误把模块对象当成模板路径传入了。比如错误写法:

    # 错误示例:传入了模块对象而非字符串路径
    from django.shortcuts import render
    import myapp.templates.index
    
    def home(request):
        return render(request, myapp.templates.index)
    

    正确写法需传入模板的字符串路径:

    def home(request):
        return render(request, 'index.html')  # 确保templates目录下存在该文件
    
  • 核对settings.py的模板配置
    确认TEMPLATES配置里的路径设置无误:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [BASE_DIR / 'templates'],  # 必须是文件系统路径,不能是模块
            'APP_DIRS': True,  # 若模板存放在app的templates子目录下,需设为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',
                ],
            },
        },
    ]
    
  • 检查模板文件存放位置

    • 项目级模板:放在项目根目录的templates文件夹下
    • App级模板:放在your_app/templates/your_app/目录下(比如myapp/templates/myapp/index.html),确保Django能正确检索到
  • 排查错误的导入语句
    检查代码中是否存在误将模板文件当作模块导入的语句,这类操作会导致传入渲染函数的是模块对象而非路径字符串。

如果以上步骤未解决问题,可贴出视图函数代码、settings.py的TEMPLATES配置段,方便进一步排查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:14:57