我有以下用于自定义用户模型的代码。 任何人都可以通过仅限制超级用户访问管理网站的解决方案来帮助我。预先感谢
# UserManager is for Custom User Model to override Django's Default Model
class UserManager(BaseUserManager):
def _create_user(self, email, password, is_superuser, **extra_fields):
if not email or not password:
raise ValueError("The given username or password must not be null")
user = self.model(
email=email,
password=password,
is_superuser=is_superuser,
last_login=now,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
return self._create_user(email, password, False, **extra_fields)
def create_superuser(self, email, password=None, **extra_fields):
return self._create_user(email, password, True, **extra_fields)
class Users(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
created_at_utc = models.DateTimeField(auto_now_add=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['password']
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return self.is_admin
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
class Meta:
db_table = "users"
我拥有上述用于用户的代码,以及以下用于管理面板的代码来创建和更新用户的 任何人都可以通过限制超级用户访问管理网站的解决方案来帮助我。预先感谢
class UserCreateForm(UserCreationForm):
class Meta:
model = Users
fields = (
"email","is_admin","is_superuser",
)
class UserChangeForm(BaseUserChangeForm):
class Meta:
model = Users
fields = (
"email","is_admin",
)
class UserAdmin(BaseAdmin):
form = UserChangeForm
add_form = UserCreateForm
fieldsets = (
(None, {"fields": ("email", "password","is_active","is_admin","is_superuser")}),
)
add_fieldsets = (
(None, {
"classes": ("wide",),
"fields": ("email", "password1", "password2","is_active","is_admin","is_superuser")}
),
)
filter_horizontal = ()
list_display = ("email","is_active", )
list_filter = ("is_active", )
search_fields = ("email",)
ordering = ("email",)
# Register your models here.
admin.site.register(Users, UserAdmin)
我已经尝试了许多解决方案,以在给出登录详细信息时仅限制超级用户访问管理页面。任何人都可以通过仅限制超级用户访问管理网站的解决方案来帮助我。预先感谢
答案 0 :(得分:0)
我认为您正在寻找的字段是is_staff
,
class AbstractUser(AbstractBaseUser, PermissionsMixin):
您可以从导入该用户
from django.contrib.auth.models import AbstractUser
,您会发现它具有名为is_staff的字段,因此这基本上是布尔字段,它确定用户是否有权登录管理站点,有关更多信息,请谷歌搜索或找到下面的文章
https://www.webforefront.com/django/adminpermissions.html
我看到您已经创建了def is_staff(self)函数,但是您没有使用is_staff字段