153

我正在使用 reportlab pdfgen 创建 PDF。在 PDF 中有一个由drawImage. 为此,我需要图像的 URL 或视图中图像的路径。我设法构建了 URL,但是如何获取图像的本地路径?

我如何获得网址:

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

8 回答 8

306
# 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/'

于 2013-07-19T05:18:26.267 回答
94

编辑:如果您使用的是 Django >=3.0,请参阅Django get the static files URL in view。Django 1.X 版本回答了这个问题。

dyve 的回答很好,但是,如果您在 django 项目中使用“缓存存储”并且静态文件的最终 url 路径应该得到“散列”(例如style.css中的style.aaddd9d8d8d7.css),那么您无法使用. 相反,您必须使用模板标签来获取散列 URL。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')
于 2013-10-14T21:33:01.590 回答
31

从 Django 3.0 你应该使用from django.templatetags.static import static

from django.templatetags.static import static

...

img_url = static('images/logo_80.png')
于 2019-12-16T10:56:01.433 回答
15

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

from django.contrib.staticfiles.storage import staticfiles_storage
staticfiles_storage.url(path)
于 2016-06-21T19:05:14.480 回答
11

使用默认static标签:

from django.templatetags.static import static
static('favicon.ico')

中还有另一个标签django.contrib.staticfiles.templatetags.staticfiles(如已接受的答案),但在 Django 2.0+ 中已弃用。

于 2019-07-22T16:43:36.107 回答
7

@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)
于 2018-07-26T11:10:07.783 回答
5

如果要获取绝对 url(包括协议、主机和端口),可以使用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'
于 2019-05-06T20:45:16.080 回答
0

简而言之,你需要得到

  • STATIC_URL
  • STATIC_ROOT
  • urlpatterns
  • staticfiles
  • templatetags
  • url parameters

一切都在正确的地方,让这个工作。此外,在实时部署中,情况会有所不同,您花费 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
于 2021-11-21T05:35:59.907 回答