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)
Ken*_*ial 81
dyve的回答是不错的,但是,如果你使用你的Django项目和静态文件的最终URL路径"缓冲存储"应该得到"哈希"(如style.aaddd9d8d8d7.css从style.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)
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+ 中已被弃用。
如果你想获取绝对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)
@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)
| 归档时间: |
|
| 查看次数: |
56531 次 |
| 最近记录: |