Reputation: 1893
I am trying to reference a model (Person) from one app, in the views-file of another app. Unfortunately, I get an "unresolved reference"-error. Is it possible to reference models from other apps in Django? If so, what am I doing wrong?
Let me demonstrate with an example:
The image below shows my project. I am currently in the views.py (marked in green), in the app called "autocomplete". I want to reference a person-model in the file "models.py" (marked in red), that belongs to the app "resultregistration". However, I get the error "Unresolved reference Person", even though the class Person does exist in models.py
The file settings.py is in the athlitikos/athlitikos - folder, and manage.py is in only athlitikos (as seen in the image below)
Any help would be strongly appreciated!
Edit: I now tried running "from ..resultregistration.models import Person", because I saw that what I did in the screenshot was obviously wrong. However, then I get the error message " attempted relative import beyond top-level package"
Thank you for your time!
Upvotes: 7
Views: 19337
Reputation: 33
resultregistration.models should do it. Just make sure the app is added to the installed apps in your settings.py.
Upvotes: 0
Reputation: 31
When doing the import from pycharm, it starts looking from the level of your present file, which is autocomplete/views.py
, but Django starts from the project level, which is the level of your manage.py
, so you can use from resultregistration.models import Person
directly. Even though pycharm's inspections will show you errors in the code, it will pass when you running the project.
Upvotes: 2
Reputation: 134
I think it will work:
from athlitikos.resultregistration.models import Person
Upvotes: 0
Reputation: 12032
If we analyse your directory tree, we can see that:
athlitikos
autocomplete
views.py
resultregistration
models.py
In the views.py
in autocomplete
you can reference to other modules with relative path. Try this:
from ..resultregistration.models import Person
The first dot goes up to autocomplete
, the second dot goes up to athlitikos
. Now from there you can access resultregistration
and everything underneath.
Upvotes: 1
Reputation: 8998
mm why you repeat athlitikos?, try replacing:
from athlitikos.athlitikos.resultregistration.models import Person
with
from resultregistration.models import Person
Upvotes: 3
Reputation: 309099
If the resultregistration
app is in the project directory (the one containing manage.py
) then you shouldn't include the project name athlitikos
in the import at all. Try the following:
from resultregistration.models import Person
Upvotes: 8