Django获取静态文件URL [英] Django get the static files URL in view

查看:683
本文介绍了Django获取静态文件URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using reportlab pdfgen to create a PDF. In the PDF there is an image created by drawImage. For this I either need the URL to an image or the path to an image in the view. I managed to build the URL but how would I get the local path to the image?

我如何获取URL:

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


推荐答案

谷歌的最高成绩,我以为我会添加另一种方式来做到这一点。我个人喜欢这个,因为它将实现到Django框架。

Since this is the top result on Google, I thought I'd add another way to do this. Personally I prefer this one, since it leaves the implementation to the Django framework.

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

这篇关于Django获取静态文件URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆