0

I am making an REST API using Django Restframework It works perfectly but I get an error when I have pushed it to railway app like this

Installing SQLite3
-----> $ python manage.py collectstatic --noinput
       Traceback (most recent call last):
         File "/workspace/manage.py", line 22, in <module>
           main()
         File "/workspace/manage.py", line 18, in main
           execute_from_command_line(sys.argv)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
           utility.execute()
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute
           self.fetch_command(subcommand).run_from_argv(self.argv)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv
           self.execute(*args, **cmd_options)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute
           output = self.handle(*args, **options)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle
           collected = self.collect()
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect
           handler(path, prefixed_path, storage)
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file
           if not self.delete_file(path, prefixed_path, source_storage):
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file
           if self.storage.exists(prefixed_path):
         File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in exists
           return os.path.exists(self.path(name))
         File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 38, in path
           raise ImproperlyConfigured("You're using the staticfiles app "
       django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.

 !     Error while running '$ python 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
ERROR: failed to build: exit status 1
ERROR: failed to build: executing lifecycle: failed with status code: 145

Here is the settings.py file

"""

    Django settings for crm_project project.
    
    Generated by 'django-admin startproject' using Django 3.2.5.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/3.2/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/3.2/ref/settings/
    """
    
    from pathlib import Path
    import os
    from dotenv import load_dotenv
    load_dotenv()
    
    # Build paths inside the project like this: BASE_DIR / 'subdir'.
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = os.getenv('SECRET_KEY')
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = os.getenv('DEBUG')
    
    ALLOWED_HOSTS = [
        'boss-instrument-production.up.railway.app', '127.0.0.1']
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',  # new
        'customer',  # new
    ]
    
    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 = 'crm_project.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 = 'crm_project.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': os.getenv('PGDATABASE'),
            'USER': os.getenv('PGUSER'),
            'PASSWORD': os.getenv('PGPASSWORD'),
            'HOST': os.getenv('PGHOST'),
            'PORT': os.getenv('PGPORT'),
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/3.2/howto/static-files/
    
    STATIC_URL = '/static/'
    
    # Default primary key field type
    # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
    
    DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

I tried resolving it by adding the DISABLE_COLLECTSTATIC variable with 1 as a value as one of the env variables. It works then, but the CSS in the API pages is gone

So can anyone let me know what I can do to get rid of this error and get the CSS onto the website?

GN Vageesh
  • 322
  • 1
  • 14
  • 1
    The error is telling you that `You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.` You need to specify the `STATIC_ROOT` in the `settings.py`. For example: `STATIC_ROOT = os.path.join(BASE_DIR, "static")` – Harun Yilmaz Aug 19 '21 at 12:48
  • 2
    Does this answer your question? [Python Django: You're using the staticfiles app without having set the STATIC\_ROOT setting](https://stackoverflow.com/questions/36760549/python-django-youre-using-the-staticfiles-app-without-having-set-the-static-ro) – Harun Yilmaz Aug 19 '21 at 12:50

1 Answers1

1

You should get advantage of a tool such as WhiteNoise to setup the Django static files configuration for production. I think you are using Heroku, for this reason I just attached here a sample configuration for the Django settings.py file that should work for you.

PS: remind that Django doesn't handle your static files anymore when you set DEBUG=False

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# and here the rest of your settings
# ...

# Static files configuration
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = os.path.join(BASE_DIR, 'static/')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# ...

# Loading test/prod settings based on ENV settings
ENV = os.environ.get('ENV')

# Add this part to the production environment only
# (Heroku in this case) with DEBUG=False:
try:
    from .production_settings import *
    MIDDLEWARE.append('whitenoise.middleware.WhiteNoiseMiddleware',)
except ImportError:
    pass
Dos
  • 2,250
  • 1
  • 29
  • 39
  • I think there's a mistake at the `STATIC_URL` property. You need to specify a URL not a path. Therefore it needs to be something like `STATIC_URL = '/static/'`. You can have a look at this thread: https://stackoverflow.com/questions/37716200/whats-the-difference-between-static-url-and-static-root-in-django – Harun Yilmaz Aug 19 '21 at 14:28
  • The answer you mentioned is not updated: the `STATIC_URL` can be both a relative or absolute url, but please refer to official Django docs on how to use it correctly https://docs.djangoproject.com/en/3.2/ref/settings/#std:setting-STATIC_URL – Dos Aug 19 '21 at 14:32
  • @Dos Please note that when you use `os.path.join(BASE_DIR, 'static/')`, the static files are served via a URL such as `https://example.com/var/www/my_project/static/` since the method returns the path. – Harun Yilmaz Aug 19 '21 at 14:45