【问题标题】:How to load static images in a django template from function not from view如何从函数而不是视图加载 django 模板中的静态图像
【发布时间】:2021-02-18 04:04:36
【问题描述】:

我正在使用 django 模板通过从函数向其提供上下文对象而不是 view 来生成 pdf,它在 view 的情况下工作正常,但我无法加载本地静态图像来自函数的模板。但这在视图中是可能的,因为在那里我可以知道使用哪个基本路径。但我不能在函数中做同样的事情。

如您所见,我可以从视图中获取基本 url。在这里我可以得到,因为我有 requests 对象,但在函数中我没有任何 requests 对象。所以图片没有加载。

    html = HTML(string=html_string, base_url=request.build_absolute_uri('/'))

这就是我在函数中尝试做的事情:

    html_string = render_to_string('experiences/voucher.html', data)
    html = HTML(string=html_string, base_url=settings.STATIC_ROOT)
    result = html.write_pdf("file_new.pdf", stylesheets=[css],optimize_images=True)

我想知道如何知道我的图像在哪里,以便可以在 pdf 上呈现图像。

【问题讨论】:

    标签: python django weasyprint


    【解决方案1】:

    它不起作用,因为base_url 无法知道图像的位置,尤其是在正在运行的服务器上,所以我必须明确定义本地资源的路径,所以我做了这样的事情: 首先我在.env 文件中添加了一个环境变量:

    like HOST=http://localhost:8000 然后我在我的实际代码中得到这个 url,如下所示:

    path = os.environ["HOST"]+"/static/"
    

    最后我将此路径传递给HTML()中的base_url参数

    html = HTML(string=html_string, base_url=path)
    

    毕竟它就像一个魅力。

    【讨论】:

      猜你喜欢
      • 2016-11-24
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      • 2018-03-18
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      相关资源
      最近更新 更多