3

I want to execute the seeds.py script located in restaurants_project/scripts/. This seed file would populate my database with restaurant records based on the CSV data within the same folder by using my Django model Restaurant. I've found that the only way to include the project settings (i.e. restaurant_project.settings) along with my necessary models was to sys.path.append('MY_PROJECTS_RELATIVE_PATH') in the seeds file. I obviously don't want to do this in production (or do i?) so what's the best way to include those settings without getting the following ImportError:

ImportError: Could not import settings 'restaurants_project.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named 'restaurants_project'

Directory Tree:

|___restaurants_project
| |______init__.py
| |______pycache__
| | |______init__.cpython-34.pyc
| | |____settings.cpython-34.pyc
| |____settings.py
| |____urls.py
| |____wsgi.py
|____restaurants
| |______init__.py
| |______pycache__
| | |______init__.cpython-34.pyc
| | |____admin.cpython-34.pyc
| | |____models.cpython-34.pyc
| |____admin.py
| |____migrations
| | |______init__.py
| |____models.py
| |____tests.py
| |____views.py
|____scripts
| |______init__.py
| |______pycache__
| | |______init__.cpython-34.pyc
| |____restaurant_inspections_2014.csv
| |____seeds.py
| |____unique_restaurant_ids.txt

seeds.py:

import os, sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'restaurants_project.settings')

import django
django.setup()

import csv
csvfile = open('restaurant_inspections_2014.csv')
reader = csv.reader(csvfile)
headers = next(reader, None)

for row in reader:
  print(row)
  import pdb; pdb.set_trace()

1 Answer 1

4

The best way to write a script that uses the settings of a project is to write a custom management command:

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

Basically you should wrap your script inside a class that extends BaseCommand and put it inside the management/commands directory of an app.

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.