Django在视图中获取静态文件的URL

我正在使用reportlab pdfgen创build一个PDF。 在PDF中有一个由drawImage创build的图像。 为此我需要URL的图像或视图中的图像的path。 我设法build立的URL,但我怎么会得到图像的本地path?

我如何获取url:

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

由于这是Google的最高成绩,所以我想增加另一种方式来做到这一点。 我个人更喜欢这个,因为它将实现留给了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/' 

但是,dyve的答案是好的,但是,如果你在你的django项目上使用“cached storage”,并且静态文件的最终urlpath应该被“散列”(比如style.css中的 style.aaddd9d8d8d7.css ),那么你无法使用django.templatetags.static.static()获取精确的url。 相反,您必须使用django.contrib.staticfiles模板标签来获取哈希url。

另外,在使用开发服务器的情况下,这个模板标记方法返回非哈希的url,所以你可以使用这个代码,而不pipe它是开发还是生产的主机! 🙂

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

这是另一种方式! (在Django 1.6上testing)

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