Django:无法在 ipython shell 中创建用户

Django: Cannot create User inside ipython shell

我正在尝试在 ipython 虚拟环境中导入 Django 用户模型。我试过下面的代码

from django.contrib.auth.models import User

导致以下错误

AppRegistryNotReady: Apps aren't loaded yet.

然后从这个 ,我在 shell 中进行了设置并尝试了以下代码。

from django.conf import settings
User = settings.AUTH_USER_MODEL
User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

这导致 AttributeError: 'str' object has no attribute 'objects' . 如何在 ipython shell 中创建用户?我正在使用 Django 1.10.6, ipython 6.0.0 和 djangorestframework 3.6.2

settings.AUTH_USER_MODEL 是一个字符串,在 shell 中你可以从 django 导入 User 作为模型。

为此,运行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', 'lennon@thebeatles.com', 'johnpassword')

我已经通过使用命令

启动 ipython shell 解决了问题
python manage.py shell -i ipython