Version 1 (modified by heckj@…, 18 years ago) ( diff )

How to set up external static media with MEDIA_URL

To take advantage of the MEDIA_URL in the settings.py file for hosting your static media on a separate server, you need to do a little internal work on your templates and some work to make that setting available to the templates.

Inside a template, where you would normally have:

blah blah <img src="/img/foo.jpg" alt="this is a foo"> blah blah..

You would instead insert {{media_url}} so that it would look like:

blah blah <img src="{{media_url}}/img/foo.jpg" alt="this is a foo"> blah blah..

It generally requires a big search and replace the first time you implement it. After that, seeing other references in the templates has been enough to remind me to use {{media_url}} before any static content.

We could pass {{media_url}} in through each view, but since we'll want it throughout the site, it's often easier to set up a simple context processor to do the heavy lifting.

Here's a example snippet from a context process:

from myproject import constants
from django.conf import settings

def common(request):
    ctx = {}
    ctx['constants'] = constants
    ctx['media_url'] = settings.MEDIA_URL
    ... more stuff here ...
    return ctx

Then in the settings.py under TEMPLATE_CONTEXT_PROCESSORS, we added:

"myproject.context_processors.common",

and from there, the MEDIA_URL in settings.py became available in all templates as {{media_url}}.

Note: See TracWiki for help on using the wiki.
Back to Top