简体   繁体   中英

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'. So that I can render it as PDF file using pisa.CreatePDF. I am using xhtml2pdf to generate 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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