Django Superuser Permission Issue: "You don’t have permission to view or edit anything"

I'm encountering an issue in my Django project where I'm unable to access the admin site as a superuser. When I try to log in as a superuser, I receive the error message: "You don’t have permission to view or edit anything." I've followed the standard steps for creating a superuser and configuring my custom user model, but I can't figure out why this permission issue is occurring.

- Django administration:  
  Site Administration, You don’t have permission to view or edit anything.*  
  \---------------------------------*

*  
for fresh start*

- deleted migrations
- deleted db.sqlite3

--------------------------------

powershell:

>>Python manage.py makemigrations
Migrations for 'auth_app':
  auth_app\migrations\0001_initial.py
    - Create model CustomUser

>>Python manage.py migrate
 Operations to perform:
  Apply all migrations: admin, auth, auth_app, contenttypes, sessions
 Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying auth_app.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying sessions.0001_initial... OK

>> python manage.py createsuperuser
 Email: helloadmin@mail.com
 Name: helloname
 Password:
 Password (again):
 This password is too short. It must contain at least 8 characters.
 This password is too common.
 This password is entirely numeric.
 Bypass password validation and create user anyway? [y/N]: y
 Superuser created successfully.

>>python manage.py runserver
 Watching for file changes with StatReloader
 Performing system checks...
 System check identified no issues (0 silenced).
 October 12, 2023 - 20:31:50
 Django version 4.2.5, using settings 'projectlogin.settings'
 Starting development server at http://127.0.0.1:8000/
 Quit the server with CTRL-BREAK.

models.py file:

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models

class CustomUserManager(BaseUserManager):
  def create_user(self, email, name, password=None):
    if not email:
      raise ValueError('User must have an email address')
    if not name:
      raise ValueError('User must have a name')
    email = self.normalize_email(email)

    user = self.model(
      email=email,
      name=name,
    )

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

    return user

  def create_superuser(self, email, password, name, **extra_fields):
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)
    extra_fields.setdefault('is_active', True)

    if extra_fields.get('is_staff') is not True:
      raise ValueError(_('Superuser must have is_staff=True.'))
    if extra_fields.get('is_superuser') is not True:
      raise ValueError(_('Superuser must have is_superuser=True.'))

    return self.create_user(email, name=name, password=password)


class CustomUser(AbstractBaseUser, PermissionsMixin):
  email = models.EmailField(unique=True)
  name = models.CharField(max_length=50)
  is_staff = models.BooleanField(default=True)
  is_active = models.BooleanField(default=True)
  is_superuser = models.BooleanField(default=False)

  REQUIRED_FIELDS = ['name']
  USERNAME_FIELD = 'email'
  objects = CustomUserManager()

  def __str__(self):
    return self.email

settings.py file:

from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = True

ALLOWED_HOSTS = []

AUTH_USER_MODEL = 'auth_app.CustomUser' # Custom User Model

INSTALLED_APPS = [
    
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'auth_app.apps.AuthAppConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'projectlogin.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ["templates"],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
WSGI_APPLICATION = 'projectlogin.wsgi.application'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

urls.py file:


from django.contrib import admin
from django.urls import path, include


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('auth_app.urls')),  # Include your app's URL patterns here
    
]


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation