So far I haven’t really used Django for “web sites”. It’s really been used as a data backend. Well the time has come for some web stuff. It’s set up to use a dev, staging, and production server. All is well and good. But each has a different media server. In Django, how do you tell it to use different media servers in the template?
A couple points. First, Django templates can extend other templates. So even if you have 1,000 templates (?!) but they all extend one basic template (often named
"base.html") then changing the
base.html updates them all. Keeps things DRY. Python is big on that and it’s good.
And to keep this process DRY, there is a context processor which can automatically provide data for your templates, i.e. a
"media_url" variable. Better still, if you use Django’s generic views, any template context processor defined in your site’s settings will automatically be passed in.
James has a great writeup about this process explaining it. In fact, he even has template util library for just this very thing among others.
A recent example that came up on the django-users mailing list was a template tag to retrieve the base URL
for your media (typically you want to store “media” like images,
possibly even have a separate server for them if you’re using Apache
and mod_python — incurring the overhead of mod_python on a request
which will just serve up a file from disk wastes resources). Django
lets you specify where your media files come from via the MEDIA_URL setting.
As it turns out, Django provides an extremely easy way to do this.
Every time you render a template, you give it a “context”; this is a
dictionary-like object whose keys are variable names and whose values
are the values of the variables. When you render a template with a
given context, every key in the context dictionary becomes a variable
in the template that you can access and use.