I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).
Edit: At the moment, I can launch it by navigating to a URL...
How do I setup the environment for this?
Although it is not recommended to run python scripts from Django shell, this is a great way to run background tasks. This is because when you run python scripts from Django shell, it gives you access to all models, views and functions defined in your Django project.
Just add it to the python path and thats it or is it a better way to go? If you place them in a folder you need to add a file called __init__.py to the folder. It can be empty. After that you should be able to import files from the folder.
The easiest way to do this is to set up your script as a manage.py
subcommand. It's quite easy to do:
from django.core.management.base import NoArgsCommand, make_option class Command(NoArgsCommand): help = "Whatever you want to print here" option_list = NoArgsCommand.option_list + ( make_option('--verbose', action='store_true'), ) def handle_noargs(self, **options): ... call your script here ...
Put this in a file, in any of your apps under management/commands/yourcommand.py (with empty __init__.py
files in each) and now you can call your script with ./manage.py yourcommand
.
If you're using Django 1.10 or greater NoArgsCommand has been deprecated. Use BaseCommand instead. https://stackoverflow.com/a/45172236/6022521
from <Project path> import settings #your project settings file from django.core.management import setup_environ #environment setup function setup_environ(settings) #Rest of your django imports and code go here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With