Import Django settings from external script

女生的网名这么多〃 提交于 2019-12-13 07:09:42

问题


I have a python script within my Django project designed to run seperate from the Django app. I want to use the settings.py on my Django App how can I do that.

When I try to import

from django.conf import settings

i get

ImportError: No module named DjangoTastypie.settings

My project Structure

I am running using eclipse-> Run as python


回答1:


Read https://docs.djangoproject.com/en/1.9/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage

So you basically will need to put this at the beginning of your script

import os
import django
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()



回答2:


Based on @Sardorbek Imomaliev, you should also make your DjangoTastypie in your PYTHONPATH, you can do this in your script.

import os
import sys
import django
from django.conf import settings

sys.path.append("path/to/DjangoTastypie")  # path to the parent dir of DjangoTastypie
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()


来源:https://stackoverflow.com/questions/38196334/import-django-settings-from-external-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!