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

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

问题描述

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



in my_app1 / models.py



from my_app2.models导入内容



未解析的引用'my_app2'



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



似乎与此问题有关:
在Django项目中导入应用



但是我无法弄清楚我在做什么错。如果我尝试:



从..my_app2.models导入东西



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



ValueError:尝试了相对顶级包之外的相对导入



编辑:



项目结构:

  my_project / 
src /
manage.py
db.sqlite3
my_app1 /
模板/
__init.py__
admin.py
models.py
urls.py
views.py
...
my_app2 /
模板/
__init.py__
admin.py
models.py
urls.py
views.py
...
my_project_app /
设置/
__init.py__
urls.py
...


解决方案

我有这个使用 Django的2个瓢项目布局,例如

  / project_root 
/ project_dir
/配置
/设置
/ my_app
/测试
models.py
/要求
readme.rst

该代码正在运行,但是在/ tests中,IntelliJ / PyCharm显示了未解决的引用:



<$来自my_app.models的p $ p> 导入

code> __ init __。py 文件到位。我最终不得不将源根目录设置为 project_dir



右键单击project_dir,将目录标记为>来源根源


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

in my_app1/models.py:

from my_app2.models import thing

"Unresolved reference 'my_app2'"

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.

It seems related to this question: Import app in django project

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

from ..my_app2.models import thing

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

ValueError: attempted relative import beyond top-level package

EDIT:

Project structure:

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
         ...

解决方案

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

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

from my_app.models import Something

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

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

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

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