对此有很多疑问,但它们似乎都与我需要的略有不同。
我在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中创建一个组,但是我想将其硬编码到admin.py中。我该怎么办?
答案 0 :(得分: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