Django Get absolute url for static files

前端 未结 6 643
孤独总比滥情好
孤独总比滥情好 2021-01-07 22:38

In Django, when I use:

{{ request.build_absolute_uri }}{% static \"img/myimage.jpg\" %}

It produces: \'http://myurl.com//static/img/myimage

6条回答
  •  生来不讨喜
    2021-01-07 23:34

    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.

提交回复
热议问题