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

olo*_*fom 126 django django-views django-staticfiles

我正在使用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"
Run Code Online (Sandbox Code Playgroud)

dyv*_*yve 269

由于这是谷歌的最佳结果,我想我会添加另一种方法来实现这一目标.我个人更喜欢这个,因为它将实现留给了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/'
Run Code Online (Sandbox Code Playgroud)

  • 在Django 2.0中,这将显示弃用通知.请使用`来自django.templatetags.static import static`. (8认同)
  • 这是一种更好的答案. (7认同)
  • 这在我在Debug中运行时不起作用(尚未尝试使用DEBUG = False).我只是将路径传递给返回的静态方法.使用Django 1.6.有什么想法吗? (3认同)
  • 你知道是否有一种干净的方法将主机名添加到静态URL(如果STATIC_URL中没有)?我需要在邮件中添加图像或其他资源,用户将无法使用相对网址查找资源. (2认同)
  • 对于任何与@Shawn(或我)有同样问题的人,这可能是因为您给出的路径以斜线开头。不要执行 `static('/style.css')`,而是执行 `static('style.css')`。 (2认同)

Ken*_*ial 81

dyve的回答是不错的,但是,如果你使用你的Django项目和静态文件的最终URL路径"缓冲存储"应该得到"哈希"(如style.aaddd9d8d8d7.cssstyle.css文件),然后你无法获得精确的网址django.templatetags.static.static().相反,您必须使用模板标记django.contrib.staticfiles来获取散列网址.

此外,在使用开发服务器的情况下,这个模板标签方法返回非混编网址,所以无论你可以使用的主机是开发或生产此代码!:)

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')
Run Code Online (Sandbox Code Playgroud)

  • 这个答案仍然得到了点击并且被积极使用,所以我用@Kenial的学分改进了我接受的答案.这仍然是此问题的首选解决方案. (4认同)

xbo*_*und 25

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

from django.templatetags.static import static

...

img_url = static('images/logo_80.png')
Run Code Online (Sandbox Code Playgroud)


Dav*_*Lam 12

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

from django.contrib.staticfiles.storage import staticfiles_storage
staticfiles_storage.url(path)
Run Code Online (Sandbox Code Playgroud)


Max*_*ysh 10

使用默认static标签:

from django.templatetags.static import static
static('favicon.ico')
Run Code Online (Sandbox Code Playgroud)

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


Mes*_*sci 8

如果你想获取绝对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'
Run Code Online (Sandbox Code Playgroud)


Jah*_*nov 6

@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)
Run Code Online (Sandbox Code Playgroud)