python - django 管理员将身份验证模型移动到另一个部分

标签 python django django-2.0

我正在使用 Django 2.x

我通过扩展 authentication 应用程序中的 AbstractModel 创建了自定义用户模型

class User(AbstractUser):
    pass

并在设置中更新

AUTH_USER_MODEL = 'authentication.User'

这导致管理面板中出现两个部分。一个部分authentication 包含User 模型,而默认Authentication and Authorization 仅包含Group 模型。

我想将 User 移动到 Authentication and Authorization 或将 Group 移动到 Authentication 以便两个模型都可以一起在一个部分。

为此,我在 authentication.admin.py

中添加了这个
apps.get_model('auth.Group')._meta.app_label = 'authentication'

Group移动到Authentication

运行后

python manage.py makemigrations

在django的auth app中生成迁移

Migrations for 'auth':
  /Users/anuj/.local/share/virtualenvs/originor_py-Vd6fDdN7/lib/python3.6/site-packages/django/contrib/auth/migrations/0010_auto_20190220_0238.py
    - Remove field permissions from group
    - Alter field groups on user
    - Delete model Group

并且在迁移迁移./manage.py migrate时,它给出了错误

ValueError: The field auth.User.groups was declared with a lazy reference to 'authentication.group', but app 'authentication' doesn't provide model 'group'.

如何将 Group 模型移动到 Django 管理中的另一个部分?
我需要创建自定义组模型吗?

最佳答案

您已经重写了继承 AbstractBaseUserPermissionsMixinAbstractUser,如下所示 类 AbstractUser(AbstractBaseUser, PermissionsMixin):

您可以在 django.contrib.auth.models.PermissionsMixin 中看到 groups 属性

class PermissionsMixin(models.Model):
    """
    A mixin class that adds the fields and methods necessary to support
    Django's Group and Permission model using the ModelBackend.
    """
    ...
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ),
        related_name="user_set",
        related_query_name="user",
    )
    ...

创建 CustomGroup 模型并将该模型添加到 groups 属性,如下所示。

class User(AbstractUser):
    ...
    groups = models.ManyToManyField(
        CustomGroup,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ),
        related_name="user_set",
        related_query_name="user",
    )
    ...

This would help you to override default Group model altered with your CustomGroup model

关于python - django 管理员将身份验证模型移动到另一个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54778982/

相关文章:

python - 在轴坐标中查找 matplotlib 图(包括刻度标签)的范围

python - 使用 Python yield 的表达式和语句有什么区别

jquery - 如何访问views.py中ajax调用发送的数据 python django

python - 分组依据和计数值

python - Django -- 新字段 : How to set default callable for existing objects

python - 如何构建正则表达式来匹配单个单词?

python - 如何有效地将 "set"(python 类型)存储在数据库中?

django - SESSION_COOKIE_HTTPONLY = True 在 Django : 中不起作用

django - 无法在 Heroku 上配置 MemCached

python - Django 2.0 : sqlite IntegrityError: FOREIGN KEY constraint failed