I've gone through just about every Python/Django import StackOverflow question and I still can't fix this issue. In Django I am trying to create a new model that has a foreign key of a model in a different app. I don't appear to be able to import this.
I am running Python 3.8 on Windows 10, running within a clean virtual environment
Steps:
> pip install django
> django-admin startproject django1
> cd django1
> python manage.py startapp app1
> python manage.py startapp app2
Add both apps to the INSTALLED_APPS in django1/settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1',
'app2'
]
Create a model in app1/models.py:
from django.db import models
class App1Model1(models.Model):
val1 = models.BooleanField()
val2 = models.BooleanField()
Create a model in app2/models.py:
from django.db import models
from ..app1.models import App1Model1
class App2Model1(models.Model):
ref1 = models.ForeignKey(App1Model1, on_delete=model.CASCASE)
Pycharm is fine with the relative import, but as soon as I run manage.py I get:
django1>python manage.py runserver
...
File "C:\DEV\sherpytest\django1\app2\models.py", line 2, in <module>
from ..app1.models import App1Model1
ValueError: attempted relative import beyond top-level package
If I change the import in app2\models.py to this:
from django.db import models
from django1.app1.models import App1Model1
class App2Model1(models.Model):
ref1 = models.ForeignKey(App1Model1, on_delete=model.CASCASE)
I get:
django1>python manage.py runserver
...
File "C:\DEV\sherpytest\django1\app2\models.py", line 2, in <module>
from django1.app1.models import App1Model1
ModuleNotFoundError: No module named 'django1.app1'
I have tried creating a setup.py in django1 and installing it to turn it into a package (even though no tutorial tells me to do that) and still having issue.
Any help is greatly appreciated :)
