Greg Friedman Greg Friedman - 4 months ago 9
Python Question

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

directory that's one below the root of the project (i.e.

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
variable and append it like the following:

import sys
path = 'Users/greg/project_name'

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:


it raises an error from the
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
, it raises an error on this line:

mod = importlib.import_module(self.SETTINGS_MODULE)


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?


You have to setup Django in your script:

import django

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

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