Slightly better media path tag

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.conf import settings
from django.template import Library

def media_path(path):
    import urlparse
    import os.path
    if os.path.exists(os.path.join(settings.MEDIA_ROOT, path)):
        return urlparse.urljoin(settings.MEDIA_URL, path)
    return ''

register = Library()
register.simple_tag(media_path)

More like this

  1. Mod to allow simple_tag to access context by leaf 5 years, 6 months ago
  2. twitter_status by zodman 5 years, 7 months ago
  3. a simple tag with context by dsblank 4 years, 4 months ago
  4. Git media cache busting tag by adamlofts 4 years, 5 months ago
  5. inclusion tag with template as variable by forgems 5 years, 2 months ago

Comments

timnik (on July 18, 2008):

This is now obsolete. You only need to import RequestContext in your views:

from django.templates import RequestContext

And then add a context_instance to your render_to_response, like so:

return render_to_response('main/main.html', {"variable": 0}, context_instance=RequestContext(request))

You can now access the media url anywhere with {{ MEDIA_URL }}

#

(Forgotten your password?)