ImportError: No module named app.models

I'm learning Django and I keep bumping into obstacles and it takes time googling to overcome the hurdle. But this one took me over 20 minutes and I still don't know the answer.

I know this is simple but I tried many things and can't seem to get access to my models.py. I keep getting the same error

Error

Traceback (most recent call last): File "import_states.py", line 11, in from app.models import State ImportError: No module named app.models

Code in Context

#!/usr/bin/env python

import csv
import os
import sys

sys.path.append("..")

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")

from app.models import State

states = State.objects.all()

for state in states:
    print state.name

Here is the path to my script folder that contains the script

/Users/ahmedawayhan/Development/projects/states/project/scripts

and here is the path to the folder that contains the models.py

/Users/ahmedawayhan/Development/projects/states/app

Any help would be appreciated.

Upvotes: 1

Views: 3686

Answers (1)

Tomasz Jakub Rup
Tomasz Jakub Rup

Reputation: 10680

Don't do this in ths way. Do it in the django-way. First read about custom management command

And add:

app/management/commands/import_states.py

from django.core.management.base import BaseCommand
from app.models import State

class Command(BaseCommand):
    def handle(self, *args, **options):

    states = State.objects.all()

    for state in states:
        print state.name

and call it:

python manage.py import_states

If You really need Your-way:

sys.path.append("../..")

or call:

python project/scripts/import_states.py

Upvotes: 1

Related Questions