I was very confused today.
I was trying to use my django app models in my python script.
here is my approach
import os, sys
sys.path.append("/var/www/cloudloon/horizon")
os.environ["DJANGO_SETTINGS_MODULE"] = "openstack_dashboard.settings"
from django.contrib.auth.models import User
I was confused why its giving me
ImportError: Could not import settings 'openstack_dashboard.settings' (Is it on sys.path?): cannot import name auth
Upon checking I created a a file called creds that includes
export PYTHONPATH=$PYTHONPATH:/var/www/cloudloon/horizon/;
export DJANGO_SETTINGS_MODULE=openstack_dashboard.settings; django-admin.py shell;
and from terminal window where creds file is located, I do
source creds
and from that django-admin.py shell, I could import any of my django app models without any errors.
Why it doesn't work in my python script?
I am done with Django, What I need to do is to create a python-daemon script that will access my django app models.
I am working with in Ubuntu 12.04 that has django 1.5
As I looking for solutions, I did this:
import os, sys
sys.path.append("/var/www/cloudloon/horizon")
sys.path.append("/var/www/cloudloon/horizon/openstack_dashboard")
# os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"openstack_dashboard.settings")
print os.environ["DJANGO_SETTINGS_MODULE"]
for s in sys.path:
print s
from django.contrib.auth.models import User
heres the output: http://paste.openstack.org/show/48787/
as you can see, the directory where settings.py is located are present on my sys.path, however, It was still unable to import openstack_dashboard.settings.
Thanks everyone.
My solution (inspired by http://blog.gabrielsaldana.org/using-django-models-in-external-python-scripts/):
import os
import sys
sys.path.append( os.path.join(os.path.dirname(__file__), 'MyDjangoProject'))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyDjangoProject.settings")
import django
from django.conf import settings
django.setup()
from myapp.models import MyModel
for s in MyModel.objects.all():
print(s)
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