Search code examples
djangofaviconcollectstaticnpm-build

Django collectstatic does not collect media files from react npm build folder


I have a frontend react app, after using npm run build it creates build folder with:

  • build
    • favicon.ico
    • index.html
    • service-woker.js
    • static

After using django's python manage.py collectstatic I noticed what django has done was that it pulls out only the static folder, favicon.ico is not pulled out. So, my website icon doesn't work.

In my index.html, <link rel="apple-touch-icon" href="%PUBLIC_URL%/favicon.ico" />

In my settings.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, '../frontend/build/static')
]
STATIC_ROOT = '/var/www/web/home/static/'
STATIC_URL = 'home/static/'

In chrome inspect in the headers element:

<link rel="icon" href="./home/favicon.ico">

How do I get it to display my web icon. Thankyou!


Solution

  • It is clear in documentation that Django collectstatic looks only for files in folders that are set in

    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, '../frontend/build/static')
    ]
    

    This will copy all files from your static folders into the STATIC_ROOT directory.

    your favicon is not in any of listed staticfiles directiories


    Second thing is that Django static files are only accessible from full STATIC_URL path ( you cannot use just .home/ path)

    Fix would be one of following

    • to simply add icon inside static folder
    • use ngnix to serve static files and add proper blocks ( prefered )
    • change STATIC_ROOT='/var/www/web/home/' and STATIC_URL = 'home/' ( note this way index.html and rest of files in home would be accessible as staticfiles)