gpt4 book ai didi

python - 为什么我不能在 Django 中导入用户模型?

转载 作者:行者123 更新时间:2023-11-28 22:29:42 25 4
gpt4 key购买 nike

我正在构建一个带有扩展 AbstractBaseUser 的自定义用户模型的 Django Web 应用程序。在我的一个模型中,我需要使用这个自定义用户模型:

from accounts.models import User

class History(models.Model):
user = models.ForeignKey(User)
job = models.ForeignKey(Job)

当我尝试运行 python manage.py makemigrations 命令时,会输出此错误消息:

ImportError: cannot import name User

在我的 settings.py 中,我执行以下操作让 django 知道有一个自定义用户模型:

AUTH_USER_MODEL = "accounts.User"

我对我做错了什么感到困惑。肯定有一种方法可以导入我不知道的这个模型。我该如何解决这个问题?

我曾尝试使用 get_user_model() 方法,但它在模型中不起作用,因为模型尚未加载。因此,这不是解决方案。还有其他想法吗?

提前谢谢你。

最佳答案

您可以进行如下操作:

from django.conf import settings
class History(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
job = models.ForeignKey(Job)

请引用documentation了解更多详情。

If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model.

get_user_model()[source]

Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active user model – the custom user model if one is specified, or User otherwise.

When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting. For example

关于python - 为什么我不能在 Django 中导入用户模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42911852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com