在管理增加员工的用户权限自定义用户模型(Add staff user permissions in

2019-09-25 18:52发布

有许多关于这个问题,但他们似乎都什么,我需要稍微不同。

我有在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 =真可以查看,更改,添加和删除记录,但不能更改超级用户或其他工作人员。 通常我会在管理员创建一个组,但我想它硬编码到admin.py。 我会怎么做呢?

现在,登录为员工用户我看到这个的时候:

Answer 1:

看看ModelAdmin.has_change_permission https://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



文章来源: Add staff user permissions in admin with custom user model