2012-07-30 65 views
91

我使用reportlab pdfgen創建PDF。在PDF中有一個由drawImage創建的圖像。爲此,我需要指向圖像的URL或視圖中圖像的路徑。我設法建立了URL,但是如何獲得圖像的本地路徑?Django獲取視圖中的靜態文件URL

我怎麼得到的網址:

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

回答

206

由於這是在谷歌上的結果,我想我會添加另一種方式來做到這一點。我個人更喜歡這個,因爲它將實現留給了Django框架。

# 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/' 
+6

這是一個更好的答案。 – CodingWithoutComments 2013-07-19 17:38:17

+2

你知道是否有一個乾淨的方式將主機名添加到靜態url(如果不存在於STATIC_URL中)? 我需要在郵件中添加圖片或其他資源,用戶將無法通過相關地址查找資源。 – gepatino 2013-09-12 20:00:13

+3

在Debug中運行時,這對我不起作用(還沒有試過DEBUG = False)。我只是獲得傳遞給返回的靜態方法的路徑。使用Django 1.6。有什麼想法嗎? – Shawn 2013-12-12 16:40:30

66

dyve的回答是不錯的,但是,如果你使用你的Django項目和靜態文件的最終URL路徑「緩衝存儲」應該得到「哈希」(如style.aaddd9d8d8d7.css from style.css),那麼你不能得到一個精確的網址與django.templatetags.static.static()。相反,您必須使用django.contrib.staticfiles中的模板標記來獲取散列網址。

此外,在使用開發服務器的情況下,此模板標記方法會返回非哈希url,因此您可以使用此代碼,而不管它是開發還是生產的主機! :)

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') 
+1

感謝這...讓我花了一段時間來弄清楚爲什麼我沒有讓我的MD5哈希注入 – ilovett 2014-05-25 02:29:31

+0

@ilovett我的榮幸! :) – Kenial 2014-05-26 05:47:22

+0

感謝您提高我的答案! – dyve 2014-07-11 18:57:45

6

這是另一種方式! (在Django 1.6上測試)

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