2013-06-26 37 views
0

我寫的Python文件中的應用程序目錄,我想從我的數據庫的名字得到一個用戶,然後在腳本中獨立做一些事情。Django的導入用戶獨立

我試過如下:

from django.contrib.auth.models import User 
user = User.objects.filter(username='xiaofei') 
print user 

但:

Traceback (most recent call last): 
    File "send_test.py", line 1, in <module> 
    from django.contrib.auth.models import User 
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 5, in <module> 
    from django.db import models 
    File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 11, in <module> 
    if DEFAULT_DB_ALIAS not in settings.DATABASES: 
    File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 184, in inner 
    self._setup() 
    File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 40, in _setup 
    raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) 
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. 

最終的解決方案:

import os, sys 
sys.path.insert(0, os.path.join(os.path.abspath('..'))) 
import settings 
from django.core.management import setup_environ 
setup_environ(settings) 

from django.contrib.auth.models import User 
user = User.objects.filter(username='xiaofei') 
print user 

回答

0

您需要perform a few tasks manually當編寫獨立的Django腳本時。

+0

我搜索「獨立Django的腳本」,並找到類似於您推薦的博客的答案,但在[這個問題(答案http://stackoverflow.com/questions/2444879/use-the- django-orm-in-a-standalone-script)再次將我的腳本移動到設置文件夾後非常有幫助 – metaphy