Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: Could not import settings. Is it in path?

Tags:

python

django

I'm getting an import error while I try to run a script in my Django app.

It is related to the settings file.

Error:

  File "bookd/get_data.py", line 10, in <module>
    from models import UserProfile
  File "/home/hiccup/DataProjects/goodread/bookda/bookd/models.py", line 3, in <module>
    from django.db import models
  File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 14, in <module>
    if not settings.DATABASES:
  File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 276, in __getattr__
    self._setup()
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 42, in _setup
    self._wrapped = Settings(settings_module)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 89, in __init__
    raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'bookda.settings' (Is it on sys.path?): No module named bookda.settings

I know its a very basic error and there have been answers to solve it but I'm just not able to solve it irrespective of whichever way I try to add the path for the settings to work. And its rather frustrating that other django apps on my system work perfectly fine.

Hierarchy:

bookda/settings.py
bookda/books/script.py

I get the error while running the script.py.

like image 298
Hick Avatar asked Jan 14 '23 11:01

Hick


1 Answers

If you're trying to write a custom script which uses your Django model[s], you'll need to ensure that Django can find your project package. Put this at the top of your script get_data.py...

import sys

sys.path.append('/home/hiccup/DataProjects/goodread')

...then it should be able to import the bookda module.

You might also have to tell Django where the settings file is, in which case you'll need...

import sys
import os

sys.path.append('/home/hiccup/DataProjects/goodread')
os.environ['DJANGO_SETTINGS_MODULE'] = 'bookda.settings'

# Now we can import Django stuff
from models import UserProfile
...
like image 55
Aya Avatar answered Jan 17 '23 14:01

Aya