Django static files on heroku

后端 未结 5 1523
借酒劲吻你
借酒劲吻你 2020-12-05 05:09

I deployed a django app to heroku, using \"git push heroku master\" which worked absolutely fine.

I then created a second app on the same git using \"heroku create s

5条回答
  •  一个人的身影
    2020-12-05 05:46

    I have been dealing with the same problem too. I tried not to use the solution recommended by David since it seems to be used only in development (and not production) (See: Heroku static files not loading, Django)

    And here are the 2 things that I changed in my code.

    (I'm using Django 1.7)

    1) settings.py

    I add these lines to the setting files

    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
    TEMPLATE_DIRS = (
        os.path.join(BASE_DIR,  'templates'),
        # Add to this list all the locations containing your static files 
    )
    

    STATIC_ROOT: this tells Django where to (a) put the static files when you run "python manage.py collectstatic" and (b) find the static files when you run the application

    TEMPLATE_DIRS: this tells Django where to look for your static files when it search for statics files when you run "python manage.py collectstatic"

    2) wsgi.py

    Originally my file was:

    import os
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxxx.settings")
    
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()
    

    And I changed it to:

    import os
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxxx.settings")
    
    from django.core.wsgi import get_wsgi_application
    from whitenoise.django import DjangoWhiteNoise
    application = get_wsgi_application()
    application = DjangoWhiteNoise(application)
    

    Read here for more information on whitenoise: https://devcenter.heroku.com/articles/django-assets#whitenoise


    Also, remember to install whitenoise: pip install whitenoise==2.0.6

    Before deploying the project, run: python manage.py collectstatic

    This will create a folder indicated by STATIC_ROOT (declared in your settings.py), containing all your static files.

提交回复
热议问题