我创建自定义用户和组如下:
models.py(我的用户应用程序)
` 从 django.db 导入模型 从 django.contrib.auth.models 导入 AbstractUser、GroupManager、Permission
class AbstractGroup(models.Model):
name = models.CharField(_("name"), max_length=150, unique=True)
permissions = models.ManyToManyField(
Permission,
verbose_name=_("permissions"),
blank=True,
related_name="fk_group_permission",
)
objects = GroupManager()
def __str__(self):
return self.name
def natural_key(self):
return (self.name,)
class Meta:
verbose_name = _("group")
verbose_name_plural = _("groups")
abstract = True
class Group(AbstractGroup):
is_active = models.BooleanField(_("Is Active"), default=True)
class User(AbstractUser):
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",
)
`
并指向settings.py:
AUTH_USER_MODEL=myusers.User AUTH_GROUP_MODEL=myusers.Group
一切正常,但是当获取组权限(a_user.get_all_permissions() 或 a_user.get_group_permissions())时引发错误: ValueError:无法查询“a_user”:必须是“Group”实例。 (这里的a_user是user用户实例) 怎么了?
get_group_permissions() 返回错误。
myproject/
├── manage.py
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
├── myusers/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── views.py
│ ├── tests.py
│ ├── migrations/
│ ├── __init__.py
myusers/models.py
from django.contrib.auth.models import AbstractUser, GroupManager, Permission
from django.db import models
from django.utils.translation import gettext_lazy as _
class AbstractGroup(models.Model):
name = models.CharField(_("name"), max_length=150, unique=True)
permissions = models.ManyToManyField(
Permission,
verbose_name=_("permissions"),
blank=True,
related_name="fk_group_permission",
)
objects = GroupManager()
def __str__(self):
return self.name
class Meta:
verbose_name = _("group")
verbose_name_plural = _("groups")
abstract = True
class Group(AbstractGroup):
is_active = models.BooleanField(_("Is Active"), default=True)
class User(AbstractUser):
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",
)
def get_group_permissions(self, obj=None):
if not self.is_active or self.is_anonymous:
return set()
permissions = Permission.objects.filter(group__user_set=self).values_list(
"content_type__app_label", "codename"
)
return {"%s.%s" % (ct, name) for ct, name in permissions}
def get_all_permissions(self, obj=None):
if not self.is_active or self.is_anonymous:
return set()
user_permissions = self.user_permissions.all().values_list(
"content_type__app_label", "codename"
)
group_permissions = self.get_group_permissions()
return {
"%s.%s" % (ct, name) for ct, name in user_permissions
} | group_permissions
myproject/settings.py
AUTH_USER_MODEL = 'myusers.User'
AUTH_GROUP_MODEL = 'myusers.Group'
使用以下命令创建超级用户:
python manage.py createsuperuser
添加新的
Group
并通过 Django 管理面板分配权限。
在 Django Shell 中测试行为:
python manage.py shell
from myusers.models import User, Group
from django.contrib.auth.models import Permission
# Create a test group
group = Group.objects.create(name="Test Group")
permission = Permission.objects.get(codename="add_user") # Example permission
group.permissions.add(permission)
# Create a test user
user = User.objects.create_user(username="testuser", password="testpassword")
user.groups.add(group)
# Fetch group permissions
print(user.get_group_permissions())
print(user.get_all_permissions())
{'auth.add_user'} # Group-level permission
{'auth.add_user'} # All permissions (group + user-level)
此代码提供了与 VS Code 兼容的实用且功能性的实现,并确保您的自定义
Group
和 User
模型无缝工作。如果您对此问题有任何疑问,请随时询问。谢谢玛贾尔!