Using DJANGO_SETTINGS_MODULE in a script in subfolder

Hi all,

Newbie here :raised_back_of_hand:. Please have mercy (and patience)!

[EDIT: solved, see my comment]

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'

I’m having a hard time understanding why this happens exactly and as a consequence, how to fix it. The various StackOverflow threads I’ve read were not easy enough for my rookie brain.

Thank you in advance for your help!

Make your script into a custom management command. This will handle setting up Django for you. Mostly you’d want to move the lines from campaign_name = ... onwards into a handle() method.

https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/

@adamchainz I didn’t know we could do this. It seems more appropriate than a script like I did, I guess, because what I’m trying to do is not a temporary “Fake data” creator for testing: it’s really supposed to allow the admin to inject new data.

Thanks a lot, really!

I also asked this question (my first time <3 ) on StackOverflow, I got a satisfying answer so I’m sharing it here: https://stackoverflow.com/questions/62461013/using-django-settings-module-in-a-script-in-subfolder