Skip to content
Advertisement

Import django models to custom python script

I am trying to create a custom python script within my Django application. This script requires the use of my app models. I am unable to figure out how to import the models appropriately to be used within this script.

My project directory:
-my_proj(name:ais)
-my_app(name:pages)
  -__init__.py
  -models.py
  -urls.py
   ...
  -utils
    -__init__.py
    -custom_script.py

So if I wanted to access the pages.models from the custom_script.py how might I do this?

I have attempted various imports such as from django.core.management import settings and from django.core.wsgi import get_wsgi_application but I still get an error stating the following:

ModuleNotFoundError: No module named 'pages'

Advertisement

Answer

There is a lot of app configuration done by Django to make your models and settings properly available. The best way to get Django to do this configuration is to make your script a management command, which will be run by python manage.py <your_script_name>. How to make your own management commands is covered by the docs. https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/

Advertisement