Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm not recognizing Django project imports: from my_app.models import thing

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          ... 
like image 809
43Tesseracts Avatar asked Jul 13 '16 04:07

43Tesseracts


People also ask

How import all models in Django?

To do this, create a directory called /«project»/«app_name»/models , inside it put __init__.py (to declare it as a module) and then create your files inside there. You then need to import your file contents into the module in __init__.py . You should read about Python modules to understand this.

Do I have to install Django for every project in PyCharm?

If you are using virtual environment for every new project then you need to install django each time. Other wise you can use single virtual environment for all the project.


1 Answers

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

like image 93
Scott Carpenter Avatar answered Sep 21 '22 22:09

Scott Carpenter