我创建了一个自定义Django管理页面。我有两种可以访问管理页面的用户(工作人员用户和超级用户)。超级用户可以查看所有用户,并可以更改其设置。他还可以添加或删除用户。员工用户只能看到他们的设置,并且可以更改其中的一些设置。我目前遇到一个问题,员工用户可以看到该Web应用程序的所有用户,并且可以添加或删除他们。我限制工作人员用户查看某些设置,但无法更改。
我不知道如何限制工作人员用户仅查看他们的设置。
这是我的代码: Admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .forms import UserAdminChangeForm, UserAdminCreationForm
from .models import UpLoadFile
User = get_user_model()
admin.site.site_header = 'SRC Orkestracija'
admin.site.index_title = 'Administration'
admin.site.register(UpLoadFile)
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserAdminChangeForm
add_form = UserAdminCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('username', 'superuser', 'active', 'staff')
list_filter = ('superuser', 'active', 'staff')
readonly_fields = [
'last_login'
]
actions = [
'activate_users',
]
filter_horizontal = ('user_permissions', 'groups')
fieldsets = (
(None, {'fields': ('username', 'password', 'config_file')}),
('Permissions', {'fields': ('superuser', 'active', 'staff', 'groups', 'user_permissions')}),
('Important dates', {'fields': ('last_login',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'config_file')}
),
)
search_fields = ('username',)
ordering = ('username',)
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
is_superuser = request.user.is_superuser
disabled_fields = set()
if not is_superuser:
disabled_fields |= {
'username',
'active',
'superuser',
'staff',
'groups',
'user_permissions'
}
if (
not is_superuser
and obj is not None
and obj == request.user
):
disabled_fields |= {
'username',
'active',
'superuser',
'staff',
'groups',
'user_permissions'
}
for f in disabled_fields:
if f in form.base_fields:
form.base_fields[f].disabled = True
return form
def activate_users(self, request, queryset):
is_superuser = request.user.is_superuser
if is_superuser:
cnt = queryset.filter(active=False).update(active=True)
self.message_user(request, 'Activated {} users.'.format(cnt))
activate_users.short_description = 'Activate Users'
admin.site.register(User, UserAdmin)
Models.py:
class UserManager(BaseUserManager):
def create_user(self, username, config_file, password=None, is_active=True, is_staff=False, is_superuser=False):
if not username:
raise ValueError("User must have username!")
if not password:
raise ValueError("User must have password!")
if not config_file:
raise ValueError("Select config file!")
user_obj = self.model(
username=username,
)
user_obj.config_file = config_file
user_obj.staff = is_staff
user_obj.superuser = is_superuser
user_obj.active = is_active
user_obj.set_password(password)
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self, username, config_file, password=None):
user = self.create_user(
username=username,
config_file=config_file,
password=password,
is_staff=True
)
return user
def create_superuser(self, username, config_file, password=None):
user = self.create_user(
username=username,
config_file=config_file,
password=password,
is_staff=True,
is_superuser=True
)
return user
class CustomUser(AbstractBaseUser, PermissionsMixin):
class Meta:
verbose_name = "User"
verbose_name_plural = "Users"
OPTIONS = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
)
username = models.CharField(unique=True, max_length=255)
active = models.BooleanField(default=True,
help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.')
staff = models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.')
superuser = models.BooleanField(default=False,
help_text='Designates that this user has all permissions without explicitly assigning them.')
config_file = models.CharField(choices=OPTIONS, max_length=255)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['config_file']
object = UserManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_lable):
return True
@property
def is_staff(self):
return self.staff
@property
def is_superuser(self):
return self.superuser
@property
def is_active(self):
return self.active
def path(user, filename):
return os.path.join(str(user))
我将感谢您提供任何帮助或说明,以了解如何添加此功能。
答案 0 :(得分:3)
您可以将超级用户设置为仅在admin类中具有添加/删除权限。
class UserAdmin(BaseUserAdmin):
...
def has_add_permission(self, request, obj=None):
if request.user.is_superuser:
return True
return False
def has_delete_permission(self, request, obj=None):
if request.user.is_superuser:
return True
return False
请注意,通过不向管理界面中的任何组或用户授予添加或删除权限,也可以实现上述目的。
以下内容仅允许所有用户为超级用户使用。否则,他们将只能更改自己的用户。
def has_change_permission(self, request, obj=None):
if request.user.is_superuser:
return True
if obj and obj.id == request.user.id:
return True
return False
如果您希望他们能够看到只有他们可见的用户的用户列表页面,则可以修改get_queryset
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(id=request.user.id)
答案 1 :(得分:0)
在您的模板中:
{% if request.user.is_superuser %}
<!-- Only superusers can view things in here -->
{% endif %}
您认为,您还必须控制可以编辑的内容和不能编辑的内容。