【问题标题】:Importing Django Custom User Model From Another App Model从另一个应用模型导入 Django 自定义用户模型
【发布时间】:2018-01-26 15:51:07
【问题描述】:

所以我有一个名为配置文件的应用程序,它有一个名为 Profile 的模型

from poros.abstracts.models import Model
from django.db import models
from poros.users.models import User


class Profile(Model):
    user = models.OneToOneField(
        to=User,
        on_delete=models.CASCADE,
        related_name='profile', )

Profile 模型有一个字段名称 user,它与我的 Django 自定义用户 User 有 OneToOneField 关系。现在的问题是它返回一个错误:

ImportError: cannot import name 'User'

我该如何解决这个问题?

【问题讨论】:

  • 不导入;在字段定义中使用appname.ModelName 格式的字符串

标签: python django django-models


【解决方案1】:

不要直接参考用户模型,django推荐参考settings.AUTH_USER_MODEL。

Document

from django.conf import settings

class Profile(Model):
    user = models.OneToOneField(
        to=settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='profile', )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2015-10-03
    • 2012-12-02
    • 2016-10-24
    相关资源
    最近更新 更多