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

VSCode中Pylance报Django项目相对导入无法解析错误,尝试多种方案未解决

问题根因

你的forms.py文件存放位置错误,导致相对导入找不到对应文件:
Django 约定templates目录仅用于存放HTML模板文件,不应存放Python代码。你当前的views.py在tunr根目录下,from .forms import ArtistForm的相对导入逻辑是查找和views.py同级目录下的forms.py,但你把forms.py放在了tunr/templates/tunr/目录下,自然无法被识别。

修复步骤

  1. 移动forms.py文件:将forms.py从tunr/templates/tunr/目录剪切到和views.py、models.py同级的tunr根目录下,调整后的文件结构如下:
tunr
     ├── apps.py
     ├── models.py
     ├── forms.py  # 移动后的正确位置
     ├── templates
     │   └── tunr
     │       ├── artist_detail.html
     │       ├── artist_form.html
     │       ├── artist_list.html
     │       ├── base.html
     │       ├── song_detail.html
     │       └── song_list.html
     └── views.py
  1. 修正VSCode配置:删除你之前在.vscode/settings.json中添加的"python.analysis.extraPaths": ["tunr/", "./tunr/templates/tunr"]配置,将templates目录加入Python分析路径属于错误操作,会引发其他导入问题。如果你是将外层项目目录而非tunr目录作为VSCode工作区打开,仅需在extraPaths中添加你实际的项目根目录路径即可。
  2. 验证修复:重启VSCode或者右键点击VSCode编辑器的命令面板,执行「Python: Restart Language Server」命令,即可看到导入报错消失。如果仍有报错,检查tunr目录下是否存在空的__init__.py文件,没有的话新建即可,该文件用于标记目录为可导入的Python包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:39:03