簡體   English   中英

django管理員將身份驗證模型移至另一部分

[英]django admin move auth models to another section

我正在使用Django 2.x

我通過擴展authentication應用程序中的AbstractModel來創建了自定義用戶模型

class User(AbstractUser):
    pass

並在設置中更新

AUTH_USER_MODEL = 'authentication.User'

這導致了管理面板中的兩個部分。 一節身份驗證包含用戶模型,而默認身份驗證和授權僅包含模型。

我想將“ 用戶”移到“ 身份驗證和授權”或“ 組”到“ 身份驗證”,以便兩個模型可以在一個部分中在一起。

為此,我將其添加到了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管理員的另一部分?
我需要創建自定義組模型嗎?

您已重寫AbstractUserclass AbstractUser(AbstractBaseUser, PermissionsMixin):繼承AbstractBaseUserPermissionsMixin ,如下class 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",
    )
    ...

這將幫助您覆蓋用CustomGroup模型更改的默認Group模型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM