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

Question:

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
         ...
Asked By: 43Tesseracts

||

Answers:

Now that I can take a look over you project structure I can tell you that the problem appears to be related to a missing __init__.py in your ‘src’ folder. Try adding an empty file named __init__.py in the root of ‘src’ folder.

Also, take a look to this question, I think is the same problem or a very similar one.

Hope this could be useful, cheers!

Answered By: pazitos10

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

Answered By: Scott Carpenter

I was having this issue after I change my environment to virtualenv, so I changed my python interpreter to my current virtualenv.

Go to File > Settings > Project Interpreter.
In that window you would be able to see all packages includes on this interpreter, Django should be there.

This worked for me.

Link about: https://intellij-support.jetbrains.com/hc/en-us/community/posts/206598665-Unresolved-Reference-Errors-for-django

Answered By: Rafael Maciel