How to execute a Python script from the Django shell?
You're not recommended to do that from the
shell - and this is intended as you shouldn't really be executing random scripts from the django environment (but there are ways around this, see the other answers).
If this is a script that you will be running multiple times, it's a good idea to set it up as a custom command ie
$ ./manage.py my_command
to do this create a file in a subdir of
commands of your
my_app/ __init__.py models.py management/ __init__.py commands/ __init__.py my_command.py tests.py views.py
and in this file define your custom command (ensuring that the name of the file is the name of the command you want to execute from
from django.core.management.base import BaseCommandclass Command(BaseCommand): def handle(self, **options): # now do the things that you want with your models here
For anyone using Django 1.7+, it seems that simply import the settings module is not enough.
After some digging, I found this Stack Overflow answer: https://stackoverflow.com/a/23241093
You now need to:
import os, djangoos.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")django.setup()# now your code can go here...
Without doing the above, I was getting a
My script file is in the same directory as my django project (ie. in the same folder as manage.py)