Why does DEBUG=False setting make my django Static Files Access fail?

后端 未结 14 2077
忘了有多久
忘了有多久 2020-11-22 05:16

Am building an app using Django as my workhorse. All has been well so far - specified db settings, configured static directories, urls, views etc. But trouble started sneaki

14条回答
  •  余生分开走
    2020-11-22 06:00

    Johnny's answer is great, but still didn't work for me just by adding those lines described there. Based on that answer, the steps that actually worked for me where:

    1. Install WhiteNoise as described:

      pip install WhiteNoise
      
    2. Create the STATIC_ROOT variable and add WhiteNoise to your MIDDLEWARE variable in settings.py:

      #settings.py
      MIDDLEWARE = [
          'django.middleware.security.SecurityMiddleware',
          'whitenoise.middleware.WhiteNoiseMiddleware', #add whitenoise
          'django.contrib.sessions.middleware.SessionMiddleware',
          ...
      ]
      
      #...
      
      STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root
      
    3. Then, modify your wsgi.py file as explained in Johnny's answer:

      #wsgi.py
      from django.core.wsgi import get_wsgi_application
      from whitenoise.django import DjangoWhiteNoise
      
      application = get_wsgi_application()
      application = DjangoWhiteNoise(application)
      
    4. After that, deploy your changes to your server (with git or whatever you use).

    5. Finally, run the collectstatic option from your manage.py on your server. This will copy all files from your static folders into the STATIC_ROOT directory we specified before:

      $ python manage.py collectstatic
      

      You will now see a new folder named staticfiles that contains such elements.

    After following these steps you can now run your server and will be able to see your static files while in Production mode.

    Update: In case you had version < 4 the changelog indicates that it's no longer necessary to declare the WSGI_APPLICATION = 'projectName.wsgi.application' on your settings.py file.

提交回复
热议问题