[Answered ]-Serving static media directly from heroku with Django

2๐Ÿ‘

I can serve static assets directly from heroku using following code:

settings.py:

MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
TINYMCE_JS_URL = MEDIA_URL + 'js/tiny_mce/tiny_mce.js'
TINYMCE_JS_ROOT = MEDIA_ROOT + 'js/tiny_mce'

urls.py:

urlpatterns = patterns('',
    ...
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True, }),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True, }),
)

base.html:

<script type="text/javascript" src="{{ MEDIA_URL }}js/tiny_mce/tiny_mce.js"></script>

<script type="text/javascript">
    tinyMCE.init({
    mode: "textareas",
    theme: "advanced",
    forced_root_block: false,
    force_p_newlines : false,
    force_br_newlines : true,
});
</script>
๐Ÿ‘คpanjianom

0๐Ÿ‘

Ok got it working using the comments in a github discussion https://github.com/aljosa/django-tinymce/pull/15

Primarily I changed the urls.py:

 urlpatterns += patterns('',
       (r'^static/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': '/app/.heroku/python/lib/python2.7/site-packages/tinymce/static/'}))

Iโ€™ve got a feeling this could be much better resolved but iโ€™m out of ideas and this works

๐Ÿ‘คKingFu

0๐Ÿ‘

For Django >= 2.0.0, For serving MEDIA_URL directly from heroku you can use

from django.urls import include, path, re_path
from django.views.static import serve


urlpatterns = [
...
re_path(r'^media/(?P<path>.*)$', serve,
        kwargs=dict(document_root=settings.MEDIA_ROOT)),
]

Remember, heroku removes MEDIA_ROOT folder with every deploy.

More info
https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted

๐Ÿ‘คwarcholprzemo

Leave a comment