djangodjango-templatesdjango-staticfilesdjango-static

django: how to load the static files with hash/md5 appending correctly?


using Django 3

I followed the Django Doc https://docs.djangoproject.com/en/3.0/ref/contrib/staticfiles/#manifeststaticfilesstorage to export my static files with a hash appending.


settings.py production

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

static_root folder (output)

 static_root/
          staticfiles.json
 static_root/css/
               project_styles.87c2920e7bc3.css
               project_styles.css

everything is collected correctly.


Afterwards i uploaded everything to my apache static server. And i set off / comment the STATICFILES_STORAGE . That is how i understand the Doc´s? If i leave this setting on in production i get an 500 Error.

settings.py production

# STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

After restarting my Django app in production, my site is still loading project_styles.css but not the hash Version project_styles.87c2920e7bc3.css in my browser. Even if i delete project_styles.css Django will not serve the hash version.

Question


Did i miss some settings in the settings.py in production mode? In the Doc´s they mention to set STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage but it shows no difference. And as it is mentioned it´s only for testing.

What i have to do to load the correct static hash version in production? do i have to set something in my templates, so that django will look into the json file for the correct hash version? Or do i have to name the hash file?


Solution

  • Alright, the Problem was that i wanted two different STATIC_ROOT Paths. One for Development and one for Production, because i want all my Development stuff in one Project folder. Because if you collectstatic with the STATIC_ROOT of your apache server, django will export it for instance into c:/var/www/your/server/static while i wanted it to c:/webprojects/myproject_1/static_root_exports and later upload these files on my server separately.

    So i set two different Path depending on DEV_STATIC off / on in my django-environ file. Django will set the correct Path.

    .env

    DEBUG=off
    # --- applies media server & sets MEDIA_ROOT & STATIC_ROOT
    DEV_STATIC=on
    
    <...>
    
    STATIC_ROOT_DEV=static_root_exports
    STATIC_ROOT_PROD=/var/www/myUserName/html/myproject_assets/static
    
    <...>
    

    setting.py

    # -- Set for Hash
    STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
    # --- STATIC_ROOT
    if DEV_STATIC == True:
        STATIC_ROOT = SERVER_DIR.joinpath(env('STATIC_ROOT_DEV'))
    else:
        STATIC_ROOT = env('STATIC_ROOT_PROD')