How to Allow Superusers to access Django Admin Panels

1.2k Views Asked by At

I have the below code for Custom Users Model. Can anyone help me out me with a Solution to restrict Access to Admin Site for Super Users only . Thanks in advance

# 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"

I have the above code for Users, and following Code for Admin Panel to create and update User's Can anyone help me out me with a Solution to restrict Access to Admin Site for Super Users only . Thanks in advance

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)

I have tried many solutions to restrict only SuperUser's to access the Admin Page when Login details are given. Can anyone help me out me with a Solution to restrict Access to Admin Site for Super Users only . Thanks in advance

2

There are 2 best solutions below

1
On BEST ANSWER

I think what you are looking for field is is_staff which is there in

class AbstractUser(AbstractBaseUser, PermissionsMixin):

you can import this user from

from django.contrib.auth.models import AbstractUser

and you will find that it has field named as is_staff, so this is basically boolean field which determines if user has access to login to admin site or not, for more info do google search or find the article below

https://www.webforefront.com/django/adminpermissions.html

I see that you have created function as def is_staff(self): but you are not using field is_staff

0
On

Had the same issue. Instead of password=None, change it to password. And pass password=password into the create_user function as you see below, together with username=username:

class MyAccountManager(BaseUserManager):
    def create_user(self, email, username, password):
        if not email:
            raise ValueError('Please add an email address')
        if not username:
            raise ValueError('Please add an username')

        user = self.model(email=self.normalize_email(
            email), username=username, password=password)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password):
        user = self.create_user(email=self.normalize_email(
            email), username=username, password=password)

        user.is_active = True
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

Hope it works for you