有许多关于这个问题,但他们似乎都什么,我需要稍微不同。
我有在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。 我会怎么做呢?
现在,登录为员工用户我看到这个的时候: