Задать вопрос

Тел: +7 965 3737 888





Serve static media files from app/media subdirectory

<p>This view will serve media files from all media subdirectories of apps in your INSTALLED_APPS setting. Save the view as media.py in your django site folder and add to urls.py:</p>
if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^media/(?P&lt;appname&gt;\w+)/(?P&lt;path&gt;.+)$', 'devel_site.media.serve_apps')

<p>Now suppose your installed apps setting looks like:
INSTALLED_APPS = ('org.myself.myapp', ...)</p>
<p>Then a request to http://localhost/media/myapp/directory/file.css will serve the file org/myself/myapp/media/directory/file.css.</p>

Вопрос полезен? Да0/Нет0

Ответы (5):

Ответ полезен? Да0/Нет0

One other note - this code is Python 2.5 specific as written. It can easily be made compatible with previous versions by replacing this line:

app_short_name = app.rpartition('.')[2]


app_short_name = app.rsplit('.', 1)[-1]

Ответ полезен? Да0/Нет0

I also have project-wide media in MEDIA_ROOT that I'd like to have served at media/. I just removed the final line (raise Http404...) and replaced it with this:

# if app not found, fall back to regular static serve from MEDIA_ROOT
full_path = "%s/%s" % (appname, path)
return serve(request, path=full_path, document_root=settings.MEDIA_ROOT)

And added this near the top:

from django.views.static import serve

Ответ полезен? Да0/Нет0

Oh right. I've overseen the if settings.DEBUG.

Ответ полезен? Да0/Нет0

phxx: Um, the suggested usage clearly indicates this is for development use, not production.

This is a great idea. It liberates me from making all those symlinks, which become a huge pain when multiple developers are working on the same project on different systems with different path setups. +1 from me, wish I'd thought of it!

Ответ полезен? Да0/Нет0

A good Idea, but i think serving media files should be the job of an apache webserver or lighttpd or something similar. It would me more usefull to make the media directory in every app a good practice and then to make symbolic links in your real media directory.