Add staff user permissions in admin with custom us

2019-07-30 18:42发布

问题:

There are a number of questions about this, but they all seem slightly different to what I need.

I have a custom user model in my core app in models.py in django:

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']

And my admin.py is like this:

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)

I would like to change the permissions for staff so that users with is_staff=True can view, change, add and delete records, but not change the superuser or other staff. Normally I would create a group in admin, but I want to hardcode it into the admin.py. How would I do this?

Right now, when logged in as a staff user I see this:

回答1:

Look at ModelAdmin.has_change_permission https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.has_change_permission

Probably something along these lines:

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