PyCharm 无法识别 Django 项目导入:from my_app.models import thing [英] PyCharm not recognizing Django project imports: from my_app.models import thing

查看:34
本文介绍了PyCharm 无法识别 Django 项目导入:from my_app.models import thing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始在我现有的 Django 项目上测试 PyCharm,它无法识别来自我项目中应用程序的任何导入:

I just started testing out PyCharm on my existing Django project, and it doesn't recognize any imports from apps within my project:

my_app1/models.py:

从 my_app2.models 导入东西

未解析的引用'my_app2'"

"Unresolved reference 'my_app2'"

这是为什么?我的项目的目录结构与 推荐的布局,而且它运行没有错误,只是PyCharm的魔法不想在它上面工作.

Why is this? My project's directory structure matches the recommended layout, and it runs without errors, it's just PyCharm's magic doesn't want to work on it.

似乎与这个问题有关:在 django 项目中导入应用

但我不知道我做错了什么.如果我尝试:

But I can't figure out what I am doing wrong. If I try:

从 ..my_app2.models 导入东西

PyCharm 错误消失了,它可以自动预测等.但是当我运行项目时 Django 抛出:

The PyCharm error goes away and it can auto predict, etc. But when I run the project Django throws:

ValueError: 尝试相对导入超出顶级包

项目结构:

my_project/
   src/
      manage.py
      db.sqlite3
      my_app1/
         templates/
         __init.py__
         admin.py
         models.py
         urls.py
         views.py
         ...
      my_app2/
         templates/
         __init.py__
         admin.py
         models.py
         urls.py
         views.py
         ...
      my_project_app/
         settings/
         __init.py__
         urls.py
         ...

推荐答案

我在使用2 Scoops of Django"项目布局时遇到了这个问题,例如

I was having this issue using a "2 Scoops of Django" project layout, e.g.

/project_root
    /project_dir
        /config
            /settings
        /my_app
            /tests
            models.py
    /requirements
    readme.rst

代码可以运行,但在/tests 中,IntelliJ/PyCharm 显示未解析的引用:

The code was working, but in /tests, IntelliJ/PyCharm showed an unresolved reference:

from my_app.models import Something

我已准备好所有 __init__.py 文件.我最终不得不将源根设置为 project_dir:

I had all the __init__.py files in place. I ended up having to set the sources root to project_dir:

右击project_dir,Mark Directory as > Sources Root

Right-click on project_dir, Mark Directory as > Sources Root

这篇关于PyCharm 无法识别 Django 项目导入:from my_app.models import thing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆