我正在使用reportlab pdfgen创建PDF。在PDF中,有一个由drawImage
创建的图像。为此,我需要图像的URL或视图中图像的路径。我已经成功构建了URL,但如何获取图像的本地路径?
如何获取URL:
prefix = 'https://' if request.is_secure() else 'http://'
image_url = prefix + request.get_host() + STATIC_URL + "images/logo_80.png"
我正在使用reportlab pdfgen创建PDF。在PDF中,有一个由drawImage
创建的图像。为此,我需要图像的URL或视图中图像的路径。我已经成功构建了URL,但如何获取图像的本地路径?
如何获取URL:
prefix = 'https://' if request.is_secure() else 'http://'
image_url = prefix + request.get_host() + STATIC_URL + "images/logo_80.png"
# 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现在包含'/static/x.jpg'
,假设静态路径为'/static/'
编辑:如果您使用的是Django >=3.0,请参考在Django中获取视图中静态文件的URL,本问题答案适用于Django 1.X版本。
dyve的回答很好,但是,如果您在django项目中使用了“缓存存储”,并且静态文件的最终url路径应该被“哈希”(例如从style.css生成的style.aaddd9d8d8d7.css),那么您不能通过django.templatetags.static.static()
得到精确的url。相反,您必须使用django.contrib.staticfiles
中的模板标签来获取哈希的url。
此外,在使用开发服务器时,此模板标签方法返回非哈希的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')
from django.templatetags.static import static
:from django.templatetags.static import static
...
img_url = static('images/logo_80.png')
<img src="{{img_url}}" alt="img_url">
。 - Artur这里有另一种方法!(在Django 1.6上测试通过)
from django.contrib.staticfiles.storage import staticfiles_storage
staticfiles_storage.url(path)
staticfiles_storage.url(path, force=True)
- Marc Gibbons使用默认的static
标签:
from django.templatetags.static import static
static('favicon.ico')
在django.contrib.staticfiles.templatetags.staticfiles
中还有另一个标签(如被接受的答案中所示),但在Django 2.0+中已被弃用。
@dyve 的答案在我的开发服务器上没有生效。相反,我使用了 find
解决了问题。以下是函数:
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)
request.build_absolute_uri
函数: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'
简单来说,您需要正确设置以下内容:
STATIC_URL
STATIC_ROOT
urlpatterns
staticfiles
templatetags
url参数
只有这些设置都正确无误,才能使程序正常运行。此外,在实时部署中,情况各不相同,很可能您在本地机器上花费3个小时设置好的内容,在服务器上却无法正常工作。
因此,我采用了传统的方式!
app
├── static
│ └── json
│ └── data.json
└── views.py
views.py
import os
with open(os.path.abspath(os.getcwd()) + '/app/static/json/data.json', 'r') as f:
pass
static('/style.css')
,而应该使用static('style.css')
。 - Djizeusfrom django.templatetags.static import static
。 - Flimm'/static'
添加到了static
函数的参数中,这是不正确的。请尝试使用static('my_file_name.xlsx')
。 - shad0w_wa1k3r