使用自定义用户模型在管理员中添加员工用户权限

Add staff user permissions in admin with custom user model

关于这个有很多问题,但它们似乎都与我需要的略有不同。

我在 django 中 models.py 的核心应用程序中有一个自定义用户模型:

from django.db import models
from django.contrib.auth.models import *

from django.contrib.auth.models import (
    AbstractBaseUser,
    BaseUserManager,
    PermissionsMixin,
)


class UserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        """Creates and saves a new user"""

        pl = Permission.objects.filter(codename__in=["add_user", "change_user", "delete_user"])

        if not email:
            raise ValueError("Users must have an email address")
        user = self.model(email=self.normalize_email(email), **extra_fields)
        user.set_password(password)
        if user.is_staff:
            user.user_permissions.add(*pl)

        user.save(using=self._db)  # required for supporting multiple databases

        return user

    def create_superuser(self, email, password):
        """Creates and saves a new superuser"""
        user = self.create_user(email, password)
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)

        return user



class User(AbstractBaseUser, PermissionsMixin):
    """Custom user model that supports using email instead of username"""

    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = "email"

    def get_list_display(self):
        return ['email']

而我的admin.py是这样的:

from django.contrib import admin
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext as _
from .models import User


class UserAdmin(BaseUserAdmin, ModelBackend):

    list_display = (
        "name",
        "email",
        "is_active",
        "is_staff",
    )

    list_display_links = ("email",)

    list_editable = (

        "name",
        "is_active",
        "is_staff",
    )

    fieldsets = (

        (None, {'fields': ('email', 'password')}),


        (_('Personal Info'), {'fields': ('name',)}),

        (

            _('Permissions'),



            {

                'fields': (

                    'is_active',

                    'is_staff',

                    'is_superuser',

                )

            }

        ),

        (_('Important dates'), {'fields': ('last_login',)}),

    )
    add_fieldsets = (

        (None, {

            'classes': ('wide',),

            'fields': ('name', 'email', 'password1', 'password2', 'is_active', 'is_staff', 'permissions')

        }),

    )
    ordering = ["id"]


admin.site.register(User, UserAdmin)

我想更改员工的权限,以便 is_staff=True 的用户可以查看、更改、添加和删除记录,但不能更改超级用户或其他员工。通常我会在管理员中创建一个组,但我想将其硬编码到 admin.py 中。我该怎么做?

现在,当我以员工用户身份登录时,我看到了:

看看ModelAdmin.has_change_permissionhttps://docs.djangoproject.com/en/2.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.has_change_permission

大概是这样的:

class UserAdmin(BaseUserAdmin, ModelBackend):

    ...

    def _allow_edit(self, obj=None):
        if not obj:
            return True
        return not (obj.is_staff or obj.is_superuser)

    def has_change_permission(self, request, obj=None):
        return self._allow_edit(obj)

    def has_delete_permission(self, request, obj=None):
        return self._allow_edit(obj)

    def has_add_permission(self, request):
        return True

    def has_view_permission(self, request, obj=None):
        return True

    def has_module_permission(self, request):
        return True