Created
February 21, 2015 21:48
-
-
Save un1t/56df90961081857650ce to your computer and use it in GitHub Desktop.
How to run scripts outside django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import os | |
import django | |
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") | |
django.setup() | |
# write your code here |
For anyone who's trying to use the above mentioned @nurettin you need to install django-extensions.
Further info : https://django-extensions.readthedocs.io/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
at the root of your project create
scripts/yourscript.py
so that you havemanage.py
andscripts
directoroy as siblings.export
DJANGO_SETTINGS_MODULE=your.settings
run
./manage.py runscript yourscript
this will load django environment and run your script within that.
you may consider putting the command in a Makefile to make it easier to manage for others.
Edit: Note that you need a
run()
function inside your scriptEdit2:
as @geekyarthurs mentioned the above requires the RunScript extension https://django-extensions.readthedocs.io/en/latest/runscript.html
The way which I've found since then which doesn't require an extension is to create a script under:
<django project>/<a django app>/management/commands/yourcommand.py
make a class derived from
BaseCommand
and implementdef handle(self, *args, **options):