2017-05-30 27 views
1

我嘗試導入Django的用戶模型在虛擬環境中的IPython無法創建用戶。我曾嘗試下面的代碼Django的:裏面的IPython Shell

from django.contrib.auth.models import User 

這導致以下錯誤

AppRegistryNotReady: Apps aren't loaded yet. 

然後從這個answer,我在外殼內部設置和嘗試下面的代碼。

from django.conf import settings 
User = settings.AUTH_USER_MODEL 
User.objects.create_user('john', '[email protected]', 'johnpassword') 

這導致AttributeError: 'str' object has no attribute 'objects' .如何創建IPython的外殼內的用戶?我正在使用Django 1.10.6, ipython 6.0.0和djangorestframework 3.6.2

+0

僅此嘗試:User.objects.create_user( '約翰', '[email protected]', 'johnpassword') - >這對我的作品。我建議你用戶「shell_plus」 –

+0

那麼,AUTH_USER_MODEL是一個字符串。你爲什麼做這個?如果您通過'manage.py shell'啓動shell,則可以正常導入用戶。 –

回答

1

我有通過使用命令

啓動IPython的殼解決了這個問題
python manage.py shell -i ipython 
2

settings.AUTH_USER_MODEL是一個字符串,在shell中你可以從django導入用戶作爲模型。

爲此,運行python manage.py shell

或者你也可以手動導入Django和設置DJANGO_SETTINGS_MODULE。

對於這一點,裏面IPython中運行這些,

import django, os 
os.environ['DJANGO_SETTINGS_MODULE'] = 'testproject.settings' 
django.setup() 

然後你就可以做,

from django.contrib.auth.models import User 

,那麼你可以在裏面喜歡這個shell創建用戶,

User.objects.create_user('john', '[email protected]', 'johnpassword') 
+0

我無法導入用戶模型,它顯示了錯誤:AppRegistryNotReady:應用都尚未加載。 – Arun

+0

做你運行'蟒蛇manage.py shell' – zaidfazil

+1

是的,我做到了。我可以在shell中導入用戶模型。當我在ipython中運行這個問題時發生問題。 – Arun