How To Run Python Script From Django

In this article we''ll show you how to run python script from Django shell,

FIrst you need to install django module

 pip install django-extensions

for more details about django-extensions visit http://django-extensions.readthedocs.org/en/latest/installation_instructions.html

Then create directory scripts and files __init__,py and <your script name>.py

mkdir scripts
touch scripts/__init__.py

touch scripts/myscript.py

 

In this example I will run python script called myscript.py , in that script write something like this :

from  mydatabase.models import Products

def run():
    # Get all products
    all_products = Products.objects.all()
    print all_products

under INSTALLED_APS in settings.py add

INSTALLED_APPS = (

    'django_extensions',
    
    
)

you can run script with command :

python  manage.py runscript myscript
 

email@djangotutsme.com Jan. 17, 2015, 4:09 a.m.