Skip to content
Advertisement

Django Pyinstaller .EXE gives me ModuleNotFoundError: No module named ‘app.urls’

I am trying to run a Django project using an EXE file compiled using Pyinstaller. But when I run the compiled .EXE file using this command I get ModuleNotFoundError: No module named 'app.urls' and another OsError: [WinError 123]. I will explain how I setup this stuff later.

Here is the full error when I run the .EXE file:

C:UsersomenDesktopdistdj>dj.exe runserver
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "threading.py", line 917, in _bootstrap_inner
  File "threading.py", line 865, in run
  File "site-packagesdjangoutilsautoreload.py", line 54, in wrapper
  File "C:UsersomenDesktopdistdjdjangocoremanagementcommandsrunserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "site-packagesdjangocoremanagementbase.py", line 390, in check
  File "site-packagesdjangocoremanagementbase.py", line 377, in _run_checks
  File "site-packagesdjangocorechecksregistry.py", line 72, in run_checks
  File "site-packagesdjangocorechecksurls.py", line 40, in check_url_namespaces_unique
  File "site-packagesdjangocorechecksurls.py", line 57, in _load_all_namespaces
  File "site-packagesdjangoutilsfunctional.py", line 80, in __get__
  File "site-packagesdjangourlsresolvers.py", line 584, in url_patterns
  File "site-packagesdjangoutilsfunctional.py", line 80, in __get__
  File "site-packagesdjangourlsresolvers.py", line 577, in urlconf_module
  File "importlib__init__.py", line 127, in import_module
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "C:UsersomenAnaconda3libsite-packagesPyInstallerloaderpyimod03_importers.py", line 627, in exec_module
    exec(bytecode, module.__dict__)
  File "djdjurls.py", line 22, in <module>
  File "site-packagesdjangourlsconf.py", line 34, in include
  File "importlib__init__.py", line 127, in import_module
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'app.urls'

Traceback (most recent call last):
  File "djmanage.py", line 24, in <module>
  File "djmanage.py", line 20, in main
  File "site-packagesdjangocoremanagement__init__.py", line 381, in execute_from_command_line
  File "site-packagesdjangocoremanagement__init__.py", line 375, in execute
  File "site-packagesdjangocoremanagementbase.py", line 323, in run_from_argv
  File "C:UsersomenDesktopdistdjdjangocoremanagementcommandsrunserver.py", line 60, in execute
    super().execute(*args, **options)
  File "site-packagesdjangocoremanagementbase.py", line 364, in execute
  File "C:UsersomenDesktopdistdjdjangocoremanagementcommandsrunserver.py", line 95, in handle
    self.run(**options)
  File "C:UsersomenDesktopdistdjdjangocoremanagementcommandsrunserver.py", line 102, in run
    autoreload.run_with_reloader(self.inner_run, **options)
  File "site-packagesdjangoutilsautoreload.py", line 598, in run_with_reloader
  File "site-packagesdjangoutilsautoreload.py", line 583, in start_django
  File "site-packagesdjangoutilsautoreload.py", line 301, in run
  File "site-packagesdjangoutilsautoreload.py", line 307, in run_loop
  File "site-packagesdjangoutilsautoreload.py", line 347, in tick
  File "site-packagesdjangoutilsautoreload.py", line 363, in snapshot_files
  File "site-packagesdjangoutilsautoreload.py", line 262, in watched_files
  File "site-packagesdjangoutilsautoreload.py", line 103, in iter_all_python_module_files
  File "site-packagesdjangoutilsautoreload.py", line 139, in iter_modules_and_files
  File "pathlib.py", line 1339, in exists
  File "pathlib.py", line 1161, in stat
OSError: [WinError 123] La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte: '<frozen importlib._bootstrap>'
[11168] Failed to execute script manage

First I installed Pyinstaller and other dependencies using the commands:

conda install -c conda-forge pyinstaller
conda install django
conda install -c conda-forge gdal
conda install -c anaconda psycopg2

Then I installed OSGeo4W64 on my Windows 10 machine for GDAL.

I added this in settings.py:

import os


if os.name == 'nt':
    import platform
    OSGEO4W = r"C:OSGeo4W"
    if '64' in platform.architecture()[0]:
        OSGEO4W += "64"
    assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W
    os.environ['OSGEO4W_ROOT'] = OSGEO4W
    os.environ['GDAL_DATA'] = OSGEO4W + r"sharegdal"
    os.environ['PROJ_LIB'] = OSGEO4W + r"shareproj"
    os.environ['PATH'] = OSGEO4W + r"bin;" + os.environ['PATH']

os.environ['DJANGO_SETTINGS_MODULE'] = 'dj.settings'

SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))

TEMPLATE_DIRS = (
    os.path.join(SETTINGS_PATH, 'templates'),
)

GEOS_LIBRARY_PATH = r'C:OSGeo4W64bingeos_c.dll'
GDAL_LIBRARY_PATH = r'C:OSGeo4W64bingdal204.dll'

I also generated a spec file using this command:

pyi-makespec dj/manage.py

And this is the generated manage.spec: (I added in datas the templates folder but it didn’t work…)

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

block_cipher = None


a = Analysis(['dj\manage.py'],
             pathex=['C:\Users\omen\Desktop'],
             binaries=[],
             datas=[('app/templates','app/templates')],
             hiddenimports=[],
             hookspath=[],
             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 )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               upx_exclude=[],
               name='manage')

Then I generated the project using this command:

pyinstaller --name=dj dj/manage.py

Also I edited libgdal.py to have the following:

# Custom library path set?
try:
    from django.conf import settings
    lib_path = settings.GDAL_LIBRARY_PATH
except (AttributeError, ImportError, ImproperlyConfigured, OSError):
    lib_path = None

Here is my main urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app.urls')),
]

And here is INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app'
]

Please help!!!

Advertisement

Answer

I able to fix this problem…

Here is what I have done:

  1. Generate spec file using pyi-makespec dj/manage.py
  2. Add app.urls in hiddenimports such as hiddenimports=['app.urls',],
  3. Use this command instead pyinstaller manage.spec

Finally!!!

Advertisement