【问题标题】:Django - render to string fails to load CSSDjango - 渲染到字符串无法加载 CSS
【发布时间】:2017-08-09 11:55:48
【问题描述】:

我正在尝试使用 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有关。

有人可以帮忙吗?

【问题讨论】:

  • 你解决了吗?我有同样的问题。谢谢克里斯。

标签: python html css django templates


【解决方案1】:

假设您的模板上下文处理器中有 Djangodjango.core.context_processors.static 或 1.10 的 django.template.context_processors.static,问题是您传递了一个简单的上下文字典,而在视图中使用 render,您会神奇地得到一个 @ 987654321@ 它会根据您在设置中使用的上下文处理器自动填充一些变量。在这种情况下,context processor 会填充一个名为 STATIC_URL 的变量,该变量等于您设置中相同变量的值。

【讨论】:

  • 我使用的是 1.8 并且在我的设置中有 context_processors.static。是否可以在上下文字典中手动添加static_url?
  • 刚刚尝试添加:context['STATIC_URL'] = '/static/',还是不行
【解决方案2】:

你可以试试:

from django.template.loader import get_template


html = get_template("my_app/sample.html")
context = {'some_key': 'some_value'}
html_content = html.render(context)
file.write(html_content)

【讨论】:

    猜你喜欢
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2018-04-24
    • 2019-03-21
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多