2

In order to populate the database of my Django application, I created a small script that reads a CSV (a list of filenames) and creates objects accordingly:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
import django
django.setup()
import csv
import sys
from myapp.models import Campaign, Annotation


campaign_name = "a_great_name"
path_to_csv = "filenames.csv"

with open(path_to_csv) as f:
    reader = csv.reader(f)
    filenames = [i[0] for i in reader]

new_campaign = Campaign.objects.create(name=campaign_name)

for i in filenames:
    new_annotation = Annotation(
        campaign=new_campaign,
        asset_loc = i)
    new_annotation.save()

I saved this script at the root of my project: myrepo/populator.py and it worked fine.

… until I decided to move it into a subfolder of my project (it’s a bit like an admin tool that should rarely be used): myrepo/useful_tools/import_filenames/populator.py

Now, when I try to run it, I get this error: ModuleNotFoundError: No module named 'myproject'

Sorry for the rookie question, but I’m having a hard time understanding why this happens exactly and as a consequence, how to fix it. Can anybody help me?

1 Answer 1

3

Yes, the problem arose when you changed the script location because then the root directory was not in the sys.path list anymore. You just need to append the root directory to the aforementioned list in order to be able to load the settings.py file of your project.

If you have the script now in myrepo/useful_tools/import_filenames/populator.py, then you will need to go back three folders down in your folders tree to be back in your root directory. For this purpose, we can do a couple of tricks using the os module.

import os
import sys

sys.path.append(os.path.abspath(os.path.join(__file__, *[os.pardir] * 3)))
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

import django
django.setup()

print('loaded!')
# ... all your script's logic

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.