Home > Blockchain >  Error deploying on Heroku - Django app - collectstatic --noinput
Error deploying on Heroku - Django app - collectstatic --noinput

Time:09-09

I'm very new trying to deploy an app on Heroku my Django app, but a got the error from above, if you have any idea, and if you look for something else out place please be free to share it because I'm junior and I'm learning. error: the code before the following error is all the packages installed on the deploying, all the packages are installed successfully and then: --->

-----> $ python project/manage.py collectstatic --noinput
       Traceback (most recent call last):
         File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 259, in fetch_command
           app_name = commands[subcommand]
       KeyError: 'collectstatic'
       During handling of the above exception, another exception occurred:
       Traceback (most recent call last):
         File "/tmp/build_f151875e/project/manage.py", line 22, in <module>
           main()
         File "/tmp/build_f151875e/project/manage.py", line 18, in main
           execute_from_command_line(sys.argv)
         File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
           utility.execute()
         File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
           self.fetch_command(subcommand).run_from_argv(self.argv)
         File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 266, in fetch_command
           settings.INSTALLED_APPS
         File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 92, in __getattr__
           self._setup(name)
         File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 79, in _setup
           self._wrapped = Settings(settings_module)
         File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 190, in __init__
           mod = importlib.import_module(self.SETTINGS_MODULE)
         File "/app/.heroku/python/lib/python3.10/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 1006, in _find_and_load_unlocked
         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 "/tmp/build_f151875e/dmcaprivacy/settings.py", line 3, in <module>
           from decouple import config
       ImportError: cannot import name 'config' from 'decouple' (/app/.heroku/python/lib/python3.10/site-packages/decouple/__init__.py)
 !     Error while running '$ python project/manage.py collectstatic --noinput'.
       See traceback above for details.
       You may need to update application code to resolve this error.
       Or, you can disable collectstatic for this application:
          $ heroku config:set DISABLE_COLLECTSTATIC=1
       https://devcenter.heroku.com/articles/django-assets
 !     Push rejected, failed to compile Python app.
 !     Push failed

manage.py:

"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dmcaprivacy.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

Settings.py:

import django_heroku
from pathlib import Path, os
from decouple import config
import os.path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool)

ALLOWED_HOSTS = ['localhost', '127.0.0.1']
ALLOWED_HOSTS = ['project.herokuapp.com']
ALLOWED_HOSTS = ['dmcaprivacy.herokuapp.com']

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',  # new
    # Local apps
    'accounts',
    'dmca',
    'crispy_forms',
    'bootstrap_modal_forms',
    # 3rd party
    'allauth',  # new
    'allauth.account',  # new
    'allauth.socialaccount',  # new
    'django_apscheduler',
    # Providers
    'allauth.socialaccount.providers.facebook',
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.twitter',

]

CRISPY_TEMPLATE_PACK = 'bootstrap4'

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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 = 'dmcaprivacy.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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',
                'dmca.context_processors.custom_processor',
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dmca',
        'USER': 'postgres',
        'PASSWORD': config('PASSWORD_DATABASE'),
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

# Password validation
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
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    )

# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
SITE_ID = 2
# SMTP Configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT')
EMAIL_USE_TLS = True
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
DEFAULT_FROM_EMAIL = config('EMAIL_HOST_USER')
SERVER_EMAIL = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",
    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)

ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
SOCIALACCOUNT_EMAIL_VERIFICATION = 'mandatory'

LOGIN_REDIRECT_URL = 'loginview'
ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login'
ACCOUNT_LOGOUT_ON_GET = True
AUTH_USER_MODEL = 'accounts.User'

django_heroku.settings(locals())

Project structure:

enter image description here

I was searching about the error and I found that trying to run the following line on the terminal on local. python manage.py collectstatic --noinput

and the result is:

Traceback (most recent call last):
  File "C:\Users\heber\PycharmProjects\Project-Dmca\project\manage.py", line 22, in <module>
    main()
  File "C:\Users\heber\PycharmProjects\Project-Dmca\project\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\heber\documents\Projects\dmcaprivacy\env\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "C:\Users\heber\documents\Projects\dmcaprivacy\env\lib\site-packages\django\core\management\__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\heber\documents\Projects\dmcaprivacy\env\lib\site-packages\django\core\management\__init__.py", line 266, in fetch_command
    settings.INSTALLED_APPS
  File "C:\Users\heber\documents\Projects\dmcaprivacy\env\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__
    self._setup(name)
  File "C:\Users\heber\documents\Projects\dmcaprivacy\env\lib\site-packages\django\conf\__init__.py", line 79, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\heber\documents\Projects\dmcaprivacy\env\lib\site-packages\django\conf\__init__.py", line 190, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'dmcaprivacy'

CodePudding user response:

You have lot of modules either not installed via pip, or not updated them via pip freeze > requirements.txt.

As such, I can identify 2 such modules:

ImportError: cannot import name 'config' from 'decouple'

Possible fix:

pip install python-decouple

2nd Error:

ModuleNotFoundError: No module named 'dmcaprivacy'

Possible fix:

Your project folder is not in correct order. Place your dmcaprivacy folder inside project folder which contains manage.py.

Then in your settings.py change:

WSGI_APPLICATION = 'dmcaprivacy.wsgi.application'

Your WSGI_APPLICATION must point to the path to your wsgi.py file.

For static files, I would recommend installing whitenoise.

Follow the steps here: http://whitenoise.evans.io/en/stable/

Finally run pip freeze > requirements.txt

  • Related