Search code examples
djangodjango-viewsdjango-staticfiles

Django get the static files URL in view


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"

Solution

  • # Older Django <3.0 (also deprecated in 2.0):
    from django.contrib.staticfiles.templatetags.staticfiles import static
    
    # Django 3.0+
    from django.templatetags.static import static
    
    url = static('x.jpg')
    

    url now contains '/static/x.jpg', assuming a static path of '/static/'