I am trying to use Django(1.8) render_to_string to convert html to pdf with management command instead of using View/request. The following code is able to convert the template to pdf. But it fails to load CSS into the template.
def html_to_pdf():
...
context = {'some_key': 'some_value'}
html = render_to_string('my_app/sample.html', context)
file.write(html)
...
sample.html
{% load static %}
<link href="{% static 'my_app/css/sample.css' %}" rel="stylesheet" type="text/css"/>
Also I have static defined in the setting file:
STATIC_URL = '/static/'
In my Django project, there is another View function which is able to load the template with CSS when the url get called. So I believe the issue has something to do with render_to_string.
Anyone can help it out?
Assuming you have django.core.context_processors.static for Django<1.10 or django.template.context_processors.static for 1.10 in your template context processors, the problem is you are passing a simple context dictionary in, whereas with render in a view you magically get a RequestContext which automatically populates a handful of variables based on what context processors you have in your settings. In this case the context processor populates a variable called STATIC_URL equal to the value of the same variable in your settings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With