Greg Friedman
Greg Friedman

Reputation: 341

Django Trouble: django.setup() throws "ImportError: No module named 'project_name'"

I've been having an issue that I believe can be solved one of 2 ways. We have a django project I am trying to write some iPython notebooks for teaching purposes and have them in a tutorials directory that's one below the root of the project (i.e. ~/tutorials).

In the beginning of the notebooks I need to import several modules but I encountered a similar problem to the one detailed in this stack overflow question: Relative imports in Python 3 , (python couldn't find the paths, even though it could when I ran the notebooks from the root directory)

My solution was to specify the absolute path to the root of the directory in a path variable and append it like the following:

import sys
path = 'Users/greg/project_name'
sys.path.append(path)

That worked and I have been able to make the imports. However, the problem I am encountering now is that when I run a function that calls get on a Django model like so:

Platform.objects.get(name='platform_name').platform_levels.get(db_name=level).id

it raises an error from the python3.4/site-packages/django/apps/registry.py file saying:

AppRegistryNotReady: Models aren't loaded yet.

Does anybody have any insight into why they aren't being loaded and what I need to do differently? Please let me know if there's other information that I should provide to help you answer this question. Thanks!

Edit: The suggestion by @albar led to a new error which I think is the root of all the issues. When I go to run django.setup(), it raises an error on this line:

mod = importlib.import_module(self.SETTINGS_MODULE)

saying:

ImportError: No module named 'project_name'

Does it need to be able to import the entire project as a module and if so, how do I tell it how to find it?

Upvotes: 2

Views: 4603

Answers (1)

albar
albar

Reputation: 3100

You have to setup Django in your script:

import django
django.setup()

EDIT: Before that, you have to define your settings module:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'

Upvotes: 2

Related Questions