Search code examples
djangoherokustaticdjango-staticfilesdjango-settings

configure Django settings for static files with Heroku


I am trying to deploy my Django website using Heroku. So far the site has deployed successfully but the only problem is collecting the static files. I am stuck with how I am supposed to configure my settings.py file so that the website knows where to find these static files.

folder structure

-website    
---App  
------Static
---------App  
---Website    
---staticfiles    
---manage.py
---Procfile    
---requirements.txt
---runtime.txt

settings.py

DEBUG = False

BASE_DIR = Path(__file__).resolve().parent.parent

MIDDLEWARE = [
   ...
   "whitenoise.middleware.WhiteNoiseMiddleware", 
   ...
]

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"), 
    os.path.join(BASE_DIR, "App/static")
] 
django_heroku.settings(locals())

STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

error msg

whitenoise.storage.MissingFileError: The file 'App/static/app/styling-images/search_button.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x0000016932C5D190>.

The CSS file 'App\styles.css' references a file which could not be found: App/static/app/styling-images/search_button.png

Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location.


Solution

  • I suspect the static files are actually being found and that the problem here is one of those files, a CSS file, uses a hardcoded url like:

    .search-button {
        background-image: url('App/static/app/styling-images/search_button.png');
        ....
    }
    

    This may work fine if DEBUG=True, but not in a production setting. You should be able to change the CSS url() to use your STATIC_URL setting as its top level, eg something like,

    .search-button {
        background-image: url('/static/app/styling-images/search_button.png');
        ....
    }
    

    (You can tell if you've got the right URL by typing it in full into your browser after your domain and seeing if it returns the image. Using the STATIC_URL s the top level should also work in your dev environment)