0

I have tried every answer on the (Django script to access model objects without using manage.py shell) stack question, and I always get error "no module name 'project_name'". My project name is called snapbackend.

I have an __init__.py setup. I know I can write django command, but that is somewhat overkill to run one function.

I am using django 2.0, and I wanted to write a script to delete old models.

import os
os.environ["DJANGO_SETTINGS_MODULE"] = "snapbackend.settings.production"
import django

django.setup()
import snapbackend
from snapbackend.models import deleteCapsuleModels

deleteCapsuleModels()
tread
  • 10,133
  • 17
  • 95
  • 170
Rahmi Pruitt
  • 569
  • 1
  • 8
  • 28

2 Answers2

-1

This is an issue with you PYTHON_PATH which seems simple but is often more tricky to figure out.

Python cannot find your django root so you need to tell python where it can find that module (not sure why it doesn't just work) but you can do this when running the script:

PYTHONPATH=../../. python your_script.py

Or the fly with:

import sys
sys.path.append('../../.')

In your case:

import os
import sys
sys.path.append('../path/to/snapbackend/.')
os.environ["DJANGO_SETTINGS_MODULE"] = "snapbackend.settings.production"
import django

The directory would depend on the relative path to your django root

tread
  • 10,133
  • 17
  • 95
  • 170
  • Using ` sys.path ` here is dangerous because it could unintentionally add additional executables into the system path. – monokrome Jul 06 '18 at 21:09
-1

This is because your module isn't installed, and it is not being run from the directory which it is inside of.

If you are using setuptools (a setup.py file), then the proper way to solve this is to symlink your project into your site packages with python setup.py develop. This will make your module available throughout your project.

If you aren't using setuptools then this is a bit trickier. If you are able to choose your current working directory when running the script, you can solve this problem by executing cd YOUR_PROJECT_DIRECTORY before running your script.

In cases where you can't mess with the current working directory, you should se the PYTHONPATH environment variable to the root of your project. This environment variable is used to add additional paths for Python to find modules within.

It's important that you don't use PATH or sys.path for security reasons. Specifically, you don't want to accidentally introdduce any executables into your system which you are unaware of.

Hope this helps!

monokrome
  • 1,377
  • 14
  • 21