django管理员将身份验证模型移至另一部分

时间:2019-02-20 04:42:02

标签: python django django-2.0

我正在使用 Django 2.x

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

class User(AbstractUser):
    pass

并在设置中更新

AUTH_USER_MODEL = 'authentication.User'

这导致管理面板中有两个部分。一部分身份验证包含 User 模型,而默认的 Authentication and Authorization 仅包含 Group 模型。

我想将用户移至身份验证和授权,或将移至身份验证,以便两个模型都可以在一起。

为此,我已将其添加到authentication.admin.py

apps.get_model('auth.Group')._meta.app_label = 'authentication'

要将移动到身份验证

运行后

python manage.py makemigrations

它在django的auth应用中生成迁移

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管理员的另一部分?
我需要创建自定义组模型吗?

1 个答案:

答案 0 :(得分:0)

您已覆盖AbstractUser,该继承了AbstractBaseUser PermissionsMixin ,如下所示 class AbstractUser(AbstractBaseUser, PermissionsMixin):

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

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",
    )
    ...
  

这将帮助您覆盖由Group模型更改的默认CustomGroup模型