Django get the static files URL in view

olofom picture olofom · Jul 30, 2012 · Viewed 67.2k times · Source

I'm using reportlab pdfgen to create a PDF. In the PDF there is an image created by drawImage. For this I either need the URL to an image or the path to an image in the view. I managed to build the URL but how would I get the local path to the image?

How I get the URL:

prefix = 'https://' if request.is_secure() else 'http://'
image_url = prefix + request.get_host() + STATIC_URL + "images/logo_80.png"

Answer

dyve picture dyve · Jul 19, 2013

Since this is the top result on Google, I thought I'd add another way to do this. Personally I prefer this one, since it leaves the implementation to the Django framework.

# Original answer said:
# from django.templatetags.static import static
# Improved answer (thanks @Kenial, see below)
from django.contrib.staticfiles.templatetags.staticfiles import static

url = static('x.jpg')
# url now contains '/static/x.jpg', assuming a static path of '/static/'