AttributeError Django & Pyinstaller (Failed to retrieve attribute INSTALLED_APPS from module...)

Viewed 104

I'm trying to build an .exe app from my Django project using PyInstaller but I'm getting an error

"AttributeError: Failed to retrieve attribute INSTALLED_APPS from module pixel.settings"

  1. I have created a project .spec file pyi-makespec -D manage.py
  2. I run this command pyinstaller manage.spec

Please tell me how to solve this problem.

My settings.py

from pathlib import Path
import os, sys
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

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 = 'pixel.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'pixel.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATICFILES_DIRS = [
    "pixel/apps/brain/static",
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = "/media/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

My manage.spec

# -*- mode: python ; coding: utf-8 -*-


block_cipher = None


a = Analysis(
    ['manage.py'],
    pathex=['C:/Users/Alex_x/Desktop/Pixel/pixel'],
    binaries=[],
    datas=[],
    hiddenimports=[
        'pixel.urls',
        'pixel.asgi',
        'pixel.settings',
        'pixel.wsgi',
        'django.contrib.admin.apps',
        'django.contrib.auth.apps',
        'django.contrib.contenttypes.apps',
        'django.contrib.sessions.apps',
        'django.contrib.messages.apps',
        'django.contrib.staticfiles.apps',
        'django.contrib.messages.middleware',
        'django.contrib.sessions.middleware',
        'django.contrib.sessions.serializers',
        'django.template.loaders',
        'django.contrib.auth.context_processors',
        'django.contrib.messages.context_processors'
    ],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    [],
    exclude_binaries=True,
    name='manage',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)
coll = COLLECT(
    exe,
    a.binaries,
    a.zipfiles,
    a.datas,
    strip=False,
    upx=True,
    upx_exclude=[],
    name='manage',
)

Full Console Error

Traceback (most recent call last):
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\utils\hooks\subproc\django_import_finder.py", line 24, in <module>
    django.setup()
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\django\__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\django\conf\__init__.py", line 87, in __getattr__
    self._setup(name)
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\django\conf\__init__.py", line 74, in _setup
    self._wrapped = Settings(settings_module)
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\django\conf\__init__.py", line 183, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Users\Alex_x\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'pixel.settings'
33360 INFO: Collecting Django migration scripts.
Traceback (most recent call last):
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 328, in get_module_attribute
    return _get_module_attribute(module_name, attr_name)
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\isolated\_parent.py", line 269, in wrapped
    return call(function, *args, **kwargs)
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\isolated\_parent.py", line 238, in call
    return isolated.call(function, *args, **kwargs)
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\isolated\_parent.py", line 176, in call
    raise RuntimeError(f"Child process call to {function.__name__}() failed with:\n" + output)
RuntimeError: Child process call to _get_module_attribute() failed with:
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\isolated\_child.py", line 63, in run_next_command
    output = function(*args, **kwargs)
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 323, in _get_module_attribute
    module = importlib.import_module(module_name)
  File "C:\Users\Alex_x\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'pixel.settings'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Alex_x\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\Alex_x\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\Alex_x\Desktop\Pixel\venv\Scripts\pyinstaller.exe\__main__.py", line 7, in <module>
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\__main__.py", line 178, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\__main__.py", line 59, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\building\build_main.py", line 842, in main
    build(specfile, distpath, workpath, clean_build)
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\building\build_main.py", line 764, in build
    exec(code, spec_namespace)
  File "manage.spec", line 7, in <module>
    a = Analysis(
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\building\build_main.py", line 319, in __init__
    self.__postinit__()
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\building\datastruct.py", line 173, in __postinit__
    self.assemble()
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\building\build_main.py", line 487, in assemble
    self.graph.process_post_graph_hooks(self)
  File "<frozen importlib._bootstrap>", line 290, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 719, in _load
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\hooks\hook-django.py", line 66, in <module>
    installed_apps = hooks.get_module_attribute(settings_module, 'INSTALLED_APPS')
  File "c:\users\alex_x\desktop\pixel\venv\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 330, in get_module_attribute
    raise AttributeError(f"Failed to retrieve attribute {attr_name} from module {module_name}") from e
AttributeError: Failed to retrieve attribute INSTALLED_APPS from module pixel.settings
1 Answers

I ran into this problem too, and fixed it. It only occurred when there was an __init__.py file in the base directory. So, the directory above the one that contains settings.py should not have an __init__.py file.

If, for some reason, you need the base directory to be a package, then this solution won't work for you. If this is the case, you'd have to fix the bug in the PyInstaller source code.

Hope this helps!

Related