Django – Absolute media URIs from templates
Sometimes, you need to build an absolute URI to a media file from your templates:
1 | http://example.com/media/sample.jpg |
After following this small tutorial, you’ll be able to do this:
1 2 | {% load mytemplatetags %} {{ media_name|absolute_media_url:request }} |
Settings
In urls.py
, in urlpatterns
, add a reverse name to the media URL:
1 2 3 4 5 6 | urlpatterns = patterns('', # Before (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), # After url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}, name="media"), ) |
You can now reverse media files using request.build_absolute_uri(reverse('media', args=['/path/to/media']))
.
In settings.py
, add django.core.context_processors.request
to TEMPLATE_CONTEXT_PROCESSORS
.
This context processor allows you to access the request.build_absolute_uri()
function from templates:
1 | {{ request.build_absolute_uri }} |
However, you can’t pass parameters to this function, so you won’t be able to reverse media path to URL. That’s why we need a filter.
Absolute url for a media
The following filter will allow you to build an absolute URL to a media. In templatetags/mytemplatetags.py
:
1 2 3 4 5 6 | ''' Usage: {{ media|absolute_media_url:request }} ''' @register.filter def absolute_media_uri(media, request): return request.build_absolute_uri(reverse('media', args=[unicode(media)])) |
Don’t forget to add a blank __init__.py
in templatetags/
or django won’t take your template tag into account.