147
votes

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"
7

7 Answers

299
votes

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/'
93
votes

dyve's answer is good one, however, if you're using "cached storage" on your django project and final url paths of the static files should get "hashed"(such as style.aaddd9d8d8d7.css from style.css), then you can't get a precise url with django.templatetags.static.static(). Instead, you must use template tag from django.contrib.staticfiles to get hashed url.

Additionally, in case of using development server, this template tag method returns non-hashed url, so you can use this code regardless of that the host it is development or production! :)

from django.contrib.staticfiles.templatetags.staticfiles import static

# 'css/style.css' file should exist in static path. otherwise, error will occur 
url = static('css/style.css')
26
votes

From Django 3.0 you should use from django.templatetags.static import static:

from django.templatetags.static import static

...

img_url = static('images/logo_80.png')
14
votes

here's another way! (tested on Django 1.6)

from django.contrib.staticfiles.storage import staticfiles_storage
staticfiles_storage.url(path)
10
votes

Use the default static tag:

from django.templatetags.static import static
static('favicon.ico')

There is another tag in django.contrib.staticfiles.templatetags.staticfiles (as in the accepted answer), but it is deprecated in Django 2.0+.

6
votes

@dyve's answer didn't work for me in the development server. Instead I solved it with find. Here is the function:

from django.conf import settings
from django.contrib.staticfiles.finders import find
from django.templatetags.static import static

def get_static(path):
    if settings.DEBUG:
        return find(path)
    else:
        return static(path)
5
votes

If you want to get absolute url(including protocol,host and port), you can use request.build_absolute_uri function shown as below:

from django.contrib.staticfiles.storage import staticfiles_storage
self.request.build_absolute_uri(staticfiles_storage.url('my-static-image.png'))
# 'http://localhost:8000/static/my-static-image.png'