2012-07-30 66 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)