-
-
Save un1t/56df90961081857650ce to your computer and use it in GitHub Desktop.
# coding: utf-8 | |
import os | |
import django | |
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") | |
django.setup() | |
# write your code here |
I was running
python ./manage.py shell < myscrip.py
If i run it just like
python myscrip.py
It gives me error
import(name)
ImportError: No module named project.settings
My script:
#!/home/django/Env/holter_dev/bin/python2
coding: utf-8
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django.setup()
if name == "main":
print 'LOOK'#!/home/django/Env/project/bin/python2
coding: utf-8
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django.setup()
if name == "main":
print 'LOOK'
This code helped me to run script with main block
import os, sys
proj_path = "/path/to/my/project/"
This is so Django knows where to find stuff.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
sys.path.append(proj_path)
This is so my local_settings.py gets loaded.
os.chdir(proj_path)
This is so models get loaded.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
at the root of your project create scripts/yourscript.py
so that you have manage.py
and scripts
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 script
Edit2:
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 implement def handle(self, *args, **options):
For anyone who's trying to use the above mentioned @nurettin you need to install django-extensions.
Further info : https://django-extensions.readthedocs.io/
In this case block in
if name == "main":
print 'LOOK'
will not work. Is it correct? or is there a way to use it?