In Django, when I use:
{{ request.build_absolute_uri }}{% static \"img/myimage.jpg\" %}
It produces: \'http://myurl.com//static/img/myimage
I just made a quick template tag for doing this. Create files /myapp/templatetags/__init__.py
and /myapp/templatetags/my_tag_library.py
, if you don't have them already, and add the following to my_tag_library.py
:
from django import template
from django.templatetags import static
register = template.Library()
class FullStaticNode(static.StaticNode):
def url(self, context):
request = context['request']
return request.build_absolute_uri(super().url(context))
@register.tag('fullstatic')
def do_static(parser, token):
return FullStaticNode.handle_token(parser, token)
Then in your templates, just {% load my_tag_library %}
and use e.g. {% fullstatic my_image.jpg %}
.
In response to earlier comments wondering why someone would need to do this, my particular use case was that I wanted to put a link to a static file inside of an open graph protocol meta tag, and those links need to be absolute. In development the static files get served locally, but in production they get served remotely, so I couldn't just prepend the host to get the full url.