Generate an image tag with a Django static url in the view instead of the template
Question: I want to generate an image with a static url in a view, then render it in a
template. I use `mark_safe` so that the HTML won't be escaped. However, it
still doesn't render the image. How do I generate the image tag in Python?

    
    
    from django.shortcuts import render
    from django.utils.safestring import mark_safe
    
    def check(request):
        html = mark_safe('<img src="{% static "brand.png" %}" />')
        return render(request, "check.html", {"image": html})
    

Rendering it in a template:

    
    
    {{ image }}
    

renders the img tag without generating the url:

    
    
    <img src="{% static "brand.png" %} />
    


Answer: You've marked the string, containing a template directive, as safe. However,
templates are rendered in one pass. When you render that string, that's it, it
doesn't go through and then render any directives that were in rendered
strings. You need to [generate the static
url](http://stackoverflow.com/a/17738606/400617) without using template
directives.

    
    
    from django.contrib.staticfiles.templatetags.staticfiles import static
    
    url = static('images/deal/deal-brand.png')
    img = mark_safe('<img src="{url}">'.format(url=url))
    

