Relative and Absolute Path in Python Django

I have succesfully, seperated my settings file to Development and Production settings.

While trying to import from base (common to the two) I always get path error.

File Structure

When I try to do this in prod.py file

from src.psm_website.settings.base import *

and try to compile with the IDE, it works well ( I used a print statement to print from a variable from the base file)

But when I try to deploy to Heroku, I get the error

from src.psm_website.settings.base import *
remote:        ModuleNotFoundError: No module named 'src'
remote:

Then when I change the import statement to this

from .base import *

I get this error when trying to deploy in heroku

raise KeyError(key) from None
remote:        KeyError: 'SECRET_KEY'

Secret key is a variable in base file, meaning base was not imported

and I get this error when I try to run from the IDE.

from .base import *
ImportError: attempted relative import with no known parent package

I have init.py in all parent directory, making them pakages from what I have read.

How can I solve this

Python Version: 3.7.7

Upvotes: 0

Views: 982

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

You don't want "src" to be a python package, only your apps and your project directory ("psm_website" in your case) should be, so first of all remove any __init__.py file from your "src" directory (and any parent directory). Python will lookup packages/modules in directories (not "packages" - just directories containaing packages) listed in it's sys.path, which by default should already begin with your current working directory.

Then you just reference the package or module by it's python qualified name, in your case from psm_website.settings.base import *. Just note that you'll have to properly set your DJANGO_SETTINGS_MODULE envvar to point to the appropriate setting file, ie DJANGO_SETTINGS_MODULE=psm_website.settings.prod etc.

NB: if you have any python import or setting using a python qualified path starting with "src", by all mean fix it, else you're almost garanteed to get double import issues (been here, done that...).

Upvotes: 1

Related Questions