【问题标题】:Django: Cannot create User inside ipython shellDjango:无法在 ipython shell 中创建用户
【发布时间】:2017-05-30 09:39:10
【问题描述】:

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

from django.contrib.auth.models import User

导致以下错误

AppRegistryNotReady: Apps aren't loaded yet.

然后从这个answer,我在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

【问题讨论】:

  • 只试试这个:User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') -> 这对我有用。我建议你使用“shell_plus”
  • 嗯,AUTH_USER_MODEL 是一个字符串。你为什么做这个?如果你通过manage.py shell 启动你的shell,你可以正常导入用户。

标签: python django django-rest-framework ipython python-3.4


【解决方案1】:

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')

【讨论】:

  • 我无法导入用户模型,它显示错误:AppRegistryNotReady:应用程序尚未加载。
  • 是的,我做到了。我可以在 shell 中导入用户模型。当我在 ipython 中运行它时会出现问题。
  • 你的 django 版本是多少?
  • 这是 Django 1.10
【解决方案2】:

我已经通过使用命令启动 ipython shell 解决了这个问题

python manage.py shell -i ipython

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 2013-09-01
    • 2023-03-13
    相关资源
    最近更新 更多