Daniel
Daniel

Reputation: 1564

serve static file with herokku, django and wsgi

I was working to deploy a website to heroku. The site seems to recognize my static files if I run with django's builtin server namely "runserver". However if I run with gunicorn The static files cannot be recognized. I was wondering if there's any special setting I need to tweak to magically make the recognition happen. Can anyone enlighten me how these two commands differ specifically or does it have anything to do with wsgi staff?

Thanks!!!

This is how I do with runserver in Procfile, which is quite neat.

web:python manage.py runserver

enter image description here And here's what I do with gunicorn in Procfile, which is a mess

web: gunicorn some.dotted.path.to.mywsgi:application

enter image description here

UPDATE

Luckily I worked around this problem by including the following line to my urls.py. Though I know it's not a perfect solution because in real word, you need to shutdown DEBUG. but as for now in development. it's working well. Can anyone explain what this line magically do?

if settings.DEBUG:
      urlpatterns += patterns('django.contrib.staticfiles.views',
                                      url(r'^static/(?P<path>.*)$', 'serve'),
                             )

Upvotes: 0

Views: 133

Answers (1)

Chris Lawlor
Chris Lawlor

Reputation: 48922

Serving static files on Heroku with Django is a bit tricky. Assuming you're using the 'staticfiles' app, you have to run 'collectstatic' to collect your static files after deploying. The problem with Heroku is that running 'collectstatic' in the shell will actually run in a new dyno, which disappears as soon as it's finished.

One potential solution is outlined here:

Basically, the idea is to combine a few commands in your Procfile so that 'collectstatic' is run during the dyno spinup process:

web: python my_django_app/manage.py collectstatic --noinput; bin/gunicorn_django --workers=4 --bind=0.0.0.0:$PORT my_django_app/settings.py 

You also have to add the 'static' views to your urls.py (see https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user, but duplicate for STATIC_URL and STATIC_ROOT). It's worth noting that the Django docs recommend against using this in production.

This solution isn't ideal though, since you are still using your gunicorn process to serve static files. IMHO the best approach to dealing with static files on Heroku is to host them on something like S3.

Upvotes: 1

Related Questions