Changes between Initial Version and Version 1 of CookBookUsingExternalMedia


Ignore:
Timestamp:
Dec 13, 2006, 6:45:31 PM (17 years ago)
Author:
heckj@…
Comment:

How to set up external static media with MEDIA_URL

Legend:

Unmodified
Added
Removed
Modified
  • CookBookUsingExternalMedia

    v1 v1  
     1To 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
     2little internal work on your templates and some work to make that setting available to the templates.
     3
     4Inside a template, where you would normally have:
     5
     6{{{
     7blah blah <img src="/img/foo.jpg" alt="this is a foo"> blah blah..
     8}}}
     9
     10You would instead insert {{media_url}} so that it would look like:
     11
     12{{{
     13blah blah <img src="{{media_url}}/img/foo.jpg" alt="this is a foo"> blah blah..
     14}}}
     15
     16It generally requires a big search and replace the first time you implement it. After that, seeing other
     17references in the templates has been enough to remind me to use {{media_url}} before any static content.
     18
     19We could pass {{media_url}} in through each view, but since we'll want it throughout the site, it's often easier to
     20set up a simple context processor to do the heavy lifting.
     21
     22Here's a example snippet from a context process:
     23
     24{{{
     25from myproject import constants
     26from django.conf import settings
     27
     28def common(request):
     29    ctx = {}
     30    ctx['constants'] = constants
     31    ctx['media_url'] = settings.MEDIA_URL
     32    ... more stuff here ...
     33    return ctx
     34}}}
     35
     36Then in the settings.py under TEMPLATE_CONTEXT_PROCESSORS, we added:
     37   "myproject.context_processors.common",
     38
     39and from there, the MEDIA_URL in settings.py became available in all templates as {{media_url}}.
Back to Top