简体   繁体   English

如何在python编码中从html模板编码动态django变量

[英]how to encode dynamic django variable from a html template in python coding

I would like to encode '{{ variable }}' and '{% for loop ...%}' from a template to a variable called 'html'. 我想将“{{variable}}”和“{%for loop ...%}”从模板编码为名为“html”的变量。 So that I can render it as PDF file using pisa.CreatePDF. 这样我就可以使用pisa.CreatePDF将其渲染为PDF文件。 I am using xhtml2pdf to generate PDF. 我使用xhtml2pdf生成PDF。

html="<html><body>{% for inventory in filter.qs %} {{ inventory.pk }} {{ inventory.name }} {{ inventory.price }} {{ inventory.quantity }} {% endfor %} </body></html>". 

the code above is not working. 上面的代码不起作用。

it doesn't give any values from database. 它没有从数据库中提供任何值。 Simply the text below: {% for inventory in filter.qs %} {{ inventory.pk }} {{ inventory.name }} {% endfor %} in the PDF output. 只需以下文字:PDF输出中的{%for inventory.qs%} {{inventory.pk}} {{inventory.name}} {%endfor%}。

Something like this: 像这样的东西:

from django.template import Template, Context

html = """
<html>
<body>
  {% for inventory in inventories %} 
    {{ inventory.pk }} {{ inventory.name }} {{ inventory.price }} {{ inventory.quantity }} 
  {% endfor %} 
</body>
</html>
"""
t = Template(html)
inventories  = Inventory.objects.all()
c = Context({'filter': filter})
raw_html = t.render(c)
print(raw_html)

See more at: https://docs.djangoproject.com/en/2.2/ref/templates/api/#rendering-a-context 有关详细信息,请访问: https//docs.djangoproject.com/en/2.2/ref/templates/api/#rendering-a-context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM