我正在使用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管理员的另一部分?
我是否需要创建自定义组模型?
你已经覆盖了继承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
模型