1

I am trying to run a standalone script in django 4.1. I have the setup as suggested in this post at the top of my file:

Django Standalone Script

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "path_to_settings.settings")
import django
django.setup()

However, on the 4th line, I get the following error:

ModuleNotFoundError: No module named 'sport_api'

This is my INSTALLED_APPS in settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # applications
    'sport_api',
    'sport_bet',

    # library
    'rest_framework',
    'corsheaders',
]

How do I get around this error?

Update:

Directory Structure

bballboy8
  • 400
  • 6
  • 25

3 Answers3

4

With just that snippet, your script should be in the same directory as manage.py.

Otherwise, if you're nesting it in Backend\sportivo\sport_api, then you need:

from pathlib import Path
import sys
BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.append(BASE_DIR.as_posix())
# ...

Depending on how nested it is, just adjust BASE_DIR with .parent as needed.

It's best to use custom management commands for standalone scripts though.

aaron
  • 39,695
  • 6
  • 46
  • 102
  • I would like to use custom management commands but I need to put it in a lambda function and as far as I know, that's not supported. – bballboy8 Oct 07 '22 at 17:35
  • I tried this several different ways and it didn't work no matter how many `.parent` I put in. – bballboy8 Oct 10 '22 at 03:24
  • Try `sys.path.append(str(BASE_DIR))` instead of `BASE_DIR.as_posix()`. – aaron Oct 10 '22 at 04:19
0

Actual module not found as you didn't give the right path

  • Try this sportivo.sport_api same for another.

  • Check this for best understanding out

0

You have to move the script to the manage.py layer. That's the only thing that got this to work for me.

bballboy8
  • 400
  • 6
  • 25