gpt4 book ai didi

django - 在 Django 中渲染 Wkhtmltopdf 中的静态文件

转载 作者:行者123 更新时间:2023-12-03 08:58:19 24 4
gpt4 key购买 nike

我已经关注了太多这个问题的答案,但我需要关于这个主题的更多解释,因为我想知道它的根本原因。

我正在尝试使用 wkhtmltopdf 创建 pdf。

这是我的设置文件,如下所示:

Settings.py

    STATIC_URL = '/static/'

STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

引用静态文件的URL是:

<link rel="stylesheet" href="{% static '/css/template_pdf.css' %}" type="text/css" />

或者

<link rel="stylesheet" href="/static/css/template_pdf.css" type="text/css" />

<link rel="stylesheet" href="file:///static/css/template_pdf.css" type="text/css" />

我也用过这个: https://gist.github.com/renyi/f02b4322590e9288ac679545df4748d3

并提供网址:

<link rel='stylesheet' type='text/css' href='{{ STATIC_URL }}static/css/template_pdf.css' />

但我理解的问题是,除了最后一个之外,上述所有内容在渲染 View 时都可以完美地工作:

def view_pdf(request):
"""View function for home page of site."""

context= {'title': 'Hello World!'}

# Render the HTML template index.html with the data in the context variable
return render(request, 'pdf/quotation.html', context=context)

但是要使用 wkhtmltopdf 创建 pdf,它特别需要指定 url,如下所示:

<link rel="stylesheet" href="http:localhost:8000/static/css/template_pdf.css" type="text/css" />

我知道我在静态文件中遗漏了一些内容。但我想知道为什么它适用于渲染模板,但不适用于使用 wkhtmltopdf 生成 pdf。我认为直接将域名放入引用网址中并不是一个好主意。

详细的解决方案会很有帮助,因为我对 django 很陌生。

我也尝试遵循这个答案,但没有任何效果:Django wkhtmltopdf don't reading static files

最佳答案

在 Debug模式下运行时,我在模板中显式添加了 http://localhost:8000:

在模板中:

<link rel="stylesheet" href="{% if debug %}http://localhost:8000{% endif %}{% static '/css/template_pdf.css' %}" type="text/css" />

我将 debug 添加到上下文中(编辑:根据 Sara 的评论,django 模板已经知道 debug 变量,因此它应该没有必要将其添加到上下文中。):

from django.conf import settings

def view_pdf(request):
"""View function for home page of site."""

context= {
'debug': settings.DEBUG,
'title': 'Hello World!'
}

# Render the HTML template index.html with the data in the context variable
return render(request, 'pdf/quotation.html', context=context)

关于django - 在 Django 中渲染 Wkhtmltopdf 中的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53238084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com