You don’t have permission to view or edit anything. Django Admin. Web-site for school - Stack Overflow
I am working on a school website where there is a superadmin who can create other users, but the regular administrators (with the is_staff permission) should not have access to the User model. However, they should have access to other models.
Currently, when I log in as a regular administrator (is_staff), I receive the error "You don’t have permission to view or edit anything." On the other hand, everything works fine when I log in as the superadmin (is_staff and is_superuser).
Could you help me figure out how to configure the permissions properly, so that the regular administrators don't have access to the User model, but can still work with other models?
managers.py
from django.contrib.auth.models import BaseUserManager
class CustomUserManager(BaseUserManager):
def _create_user(self, username, position, password, is_staff, is_superuser, **extra_fields):
if not username:
raise ValueError("Вы не ввели username!")
if not password:
raise ValueError("Вы не ввели пароль!")
user = self.model(
username=username,
position=position,
is_active=True,
is_staff=is_staff,
is_superuser=is_superuser,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, position="Администратор", password=None, **extra_fields):
return self._create_user(username, position, password, is_staff=False, is_superuser=False, **extra_fields)
def create_superuser(self, username, password=None, **extra_fields):
return self._create_user(
username,
position="Главный администратор",
password=password,
is_staff=True,
is_superuser=True,
**extra_fields
)
models.py:
from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin,
)
from django.db import models
from .managers import CustomUserManager
POSITION = [
('Главный администратор', 'Главный администратор'),
('Администратор', 'Администратор'),
]
class User(AbstractBaseUser, PermissionsMixin):
id = models.AutoField(primary_key=True, unique=True)
username = models.CharField(max_length=24, unique=True, verbose_name="Имя пользователя (на английском)")
position = models.CharField(choices=POSITION, default="Администратор", blank=False, null=False, max_length=21)
is_active = models.BooleanField(default=True, verbose_name="Активность")
is_staff = models.BooleanField(default=False, verbose_name="Администратор")
is_superuser = models.BooleanField(default=False, verbose_name="Главный администратор")
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
objects = CustomUserManager()
class Meta:
verbose_name = "Администратор"
verbose_name_plural = "Администраторы"
def __str__(self):
return self.username
def save(self, *args, **kwargs):
if self.position == "Главный администратор":
self.is_superuser = True
self.is_staff = True
elif self.position == "Администратор":
self.is_superuser = False
self.is_staff = True
super().save(*args, **kwargs)
forms.py:
from django import forms
from django.contrib.auth.forms import UserChangeForm
from .models import User
class CustomUserChangeForm(UserChangeForm):
password = forms.CharField(
widget=forms.PasswordInput(),
required=False,
help_text="Оставьте это поле пустым, если не хотите менять пароль."
)
class Meta:
model = User
fields = '__all__'
def save(self, commit=True):
user = super().save(commit=False)
password = self.cleaned_data.get('password')
if password:
user.set_password(password)
else:
user.password = User.objects.get(id=user.id).password
if commit:
user.save()
return user
admin.py:
from django.contrib import admin
from .models import User
from .forms import CustomUserChangeForm
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
form = CustomUserChangeForm
list_display = ('username', 'position')
ordering = ('username',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
('Position', {'fields': ('position', )}),
)
I am working on a school website where there is a superadmin who can create other users, but the regular administrators (with the is_staff permission) should not have access to the User model. However, they should have access to other models.
Currently, when I log in as a regular administrator (is_staff), I receive the error "You don’t have permission to view or edit anything." On the other hand, everything works fine when I log in as the superadmin (is_staff and is_superuser).
Could you help me figure out how to configure the permissions properly, so that the regular administrators don't have access to the User model, but can still work with other models?
managers.py
from django.contrib.auth.models import BaseUserManager
class CustomUserManager(BaseUserManager):
def _create_user(self, username, position, password, is_staff, is_superuser, **extra_fields):
if not username:
raise ValueError("Вы не ввели username!")
if not password:
raise ValueError("Вы не ввели пароль!")
user = self.model(
username=username,
position=position,
is_active=True,
is_staff=is_staff,
is_superuser=is_superuser,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, position="Администратор", password=None, **extra_fields):
return self._create_user(username, position, password, is_staff=False, is_superuser=False, **extra_fields)
def create_superuser(self, username, password=None, **extra_fields):
return self._create_user(
username,
position="Главный администратор",
password=password,
is_staff=True,
is_superuser=True,
**extra_fields
)
models.py:
from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin,
)
from django.db import models
from .managers import CustomUserManager
POSITION = [
('Главный администратор', 'Главный администратор'),
('Администратор', 'Администратор'),
]
class User(AbstractBaseUser, PermissionsMixin):
id = models.AutoField(primary_key=True, unique=True)
username = models.CharField(max_length=24, unique=True, verbose_name="Имя пользователя (на английском)")
position = models.CharField(choices=POSITION, default="Администратор", blank=False, null=False, max_length=21)
is_active = models.BooleanField(default=True, verbose_name="Активность")
is_staff = models.BooleanField(default=False, verbose_name="Администратор")
is_superuser = models.BooleanField(default=False, verbose_name="Главный администратор")
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
objects = CustomUserManager()
class Meta:
verbose_name = "Администратор"
verbose_name_plural = "Администраторы"
def __str__(self):
return self.username
def save(self, *args, **kwargs):
if self.position == "Главный администратор":
self.is_superuser = True
self.is_staff = True
elif self.position == "Администратор":
self.is_superuser = False
self.is_staff = True
super().save(*args, **kwargs)
forms.py:
from django import forms
from django.contrib.auth.forms import UserChangeForm
from .models import User
class CustomUserChangeForm(UserChangeForm):
password = forms.CharField(
widget=forms.PasswordInput(),
required=False,
help_text="Оставьте это поле пустым, если не хотите менять пароль."
)
class Meta:
model = User
fields = '__all__'
def save(self, commit=True):
user = super().save(commit=False)
password = self.cleaned_data.get('password')
if password:
user.set_password(password)
else:
user.password = User.objects.get(id=user.id).password
if commit:
user.save()
return user
admin.py:
from django.contrib import admin
from .models import User
from .forms import CustomUserChangeForm
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
form = CustomUserChangeForm
list_display = ('username', 'position')
ordering = ('username',)
fieldsets = (
(None, {'fields': ('username', 'password')}),
('Position', {'fields': ('position', )}),
)
Share
Improve this question
asked 21 hours ago
Шахнур КалыбековШахнур Калыбеков
11 silver badge
New contributor
Шахнур Калыбеков is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1 Answer
Reset to default 1Create a new group with specific permissions and assign it to the staff users.
- AMD、英特尔等开始疏远Windows
- [连载]巨头“心血之作”终失败(五):惠普TouchPad
- java - ChatResponse how to get the history of the ToolResponseMessage Spring ai - Stack Overflow
- c++ - Android OpenXR application java.io.FileNotFoundException: apexcom.meta.xrpriv-appVrDriverVrDriver.apk - Stack Overflow
- angularjs - Laravel Custom Auth in registering - Stack Overflow
- vuejs3 - Vue 3 Composition API data() - Generic idea required - Stack Overflow
- python - NaN values in Pandas are not being filled by the interpolate function when it's applied to a full dataframe - S
- Flutter : Privacy screen implementation - Stack Overflow
- regex - Change text block with nearest search pattern - Stack Overflow
- Why is my bot not able to detect when a user leaves in Telegram? - Stack Overflow
- python - Four MLX90640 thermal cameras on 4 custom buses in Rasberry Pi 5B - Stack Overflow
- rust - Remove struct from vector while mutably iterating through it - Stack Overflow
- Optional parentheses for C variadic macro (i.e. both function-like and object-like) - Stack Overflow
- javascript - How to Upload an Image to Supabase Storage and Store the Public URL in a Form Using Zod and React Hook Form in Next
- python - preprocessing strategies for OCR (pytesseract) character recognition - Stack Overflow
- Page Performance Issue with Countdown in Angular on Component Reload - Stack Overflow
- java - Android physical keyboard support for key press and hold - Stack Overflow