J'ai créé une page d'administration Django personnalisée. J'ai deux types d'utilisateurs qui peuvent accéder à la page d'administration (l'utilisateur du personnel et le superutilisateur). Le superutilisateur peut voir tous les utilisateurs et modifier leurs paramètres. Il peut également ajouter ou supprimer des utilisateurs. L'utilisateur du personnel ne peut voir que ses paramètres et peut en modifier certains. Je suis actuellement confronté à un problème : les membres du personnel peuvent voir tous les utilisateurs de l'application web et peuvent les ajouter ou les supprimer. J'ai limité les utilisateurs du personnel à voir certains paramètres, mais ils ne peuvent pas les modifier.
Je ne sais pas comment limiter les utilisateurs du personnel à leurs propres paramètres.
Voici mon code : 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))
J'apprécierai toute aide ou instruction sur la manière d'ajouter cette fonctionnalité.