python - Django - 呈现为字符串无法加载 CSS

标签 python html css django templates

我正在尝试使用 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/

相关文章:

python - Python中数据的高效拆分

python - 在 Anaconda python 中配置根路径

php - 如何仅向双引号添加斜杠

php - preg_replace div(或任何东西)与 class=removeMe

javascript - js有问题

python - Django 中缺少 'Median' 聚合函数?

python - Django 项目发送回类别对象而不是该类别的名称

javascript - 什么是 CSS :before, 的最佳降级:在较旧的 IE 中伪造之后

javascript - 动态组合图像和文本并使整个 div 用作超链接

html - 如何使中间div高于第一和第二