我正在尝试使用 Django(1.8) render_to_string 通过管理命令将 html 转换为 pdf,而不是使用 View/request。以下代码能够将模板转换为pdf。但是它无法将 CSS 加载到模板中。
def html_to_pdf():
...
context = {'some_key': 'some_value'}
html = render_to_string('my_app/sample.html', context)
file.write(html)
...
示例.html
{% load static %}
<link href="{% static 'my_app/css/sample.css' %}" rel="stylesheet" type="text/css"/>
我还在设置文件中定义了静态:
STATIC_URL = '/static/'
在我的 Django 元素中,有另一个 View 函数可以在调用 url 时使用 CSS 加载模板。所以我认为这个问题与 render_to_string 有关。
谁能帮帮我?
最佳答案
假设您的模板上下文处理器中有用于 Django<1.10 的 django.core.context_processors.static
或用于 1.10 的 django.template.context_processors.static
,问题是您正在传递一个简单的上下文字典,而在 View 中使用 render
您会神奇地得到一个 RequestContext
它会根据您在设置中拥有的上下文处理器自动填充一些变量。在这种情况下 context processor填充一个名为 STATIC_URL
的变量,该变量等于您设置中相同变量的值。
关于python - Django - 呈现为字符串无法加载 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865753/