Part 1这个问题被单独提出并回答。
我有Report
和ReportTemplate
。
+----+----------+---------------+-------------+
| id | title | data | template_id |
+----+----------+---------------+-------------+
| 1 | report 1 | {data: [...]} | 1 |
+----+----------+---------------+-------------+
reports table
+----+-----------+---------------+------------+
| id | title | markup | css |
+----+-----------+---------------+------------+
| 1 | template1 | <doctype!>... | body {.... |
+----+-----------+---------------+------------+
templates table
报告属于ReportTemplate。 ReportTemplate有很多报告。
我在admin.py
中为print_as_pdf
import logging
logger = logging.getLogger('reports.admin')
from django.contrib import admin
# Register your models here.
from reports.models import Report, ReportTemplate
class ReportAdmin(admin.ModelAdmin):
fields = ['commodity',
'date',
'trade_period',
'quantity_cutoff',
'data',
'template',
'title']
actions = ['print_as_pdf']
def print_as_pdf(self, request, queryset):
logger.debug('anything')
for report in queryset:
markup = report.template.markup
logger.debug(markup)
return
print_as_pdf.short_description = 'Generate as pdf'
这些是模特:
class ReportTemplate(models.Model):
title = models.CharField(max_length=50)
markup = models.TextField(default = 'markup here...')
styles = models.TextField(default = 'styles here...')
# __unicode__ on Python 2
# __str__ on Python 3
def __unicode__(self):
return self.title
class Report(models.Model):
title = models.CharField(max_length=50)
commodity = models.CharField(max_length=10)
date = models.DateTimeField('date traded')
trade_period = models.CharField(max_length=10, default='open')
quantity_cutoff = models.IntegerField(default=0)
printed = models.BooleanField(default=0)
datetime_email_sent = models.DateTimeField('date email sent', blank=True, null=True)
data = models.TextField(default = 'data here...')
template = models.ForeignKey(ReportTemplate)
我想做的是:
markup
字段值data
字段值通过markup
值放在1中,该值是用jinja2标记写的我被困在第2步。
由于我检索的标记是字符串格式,如何使用我拥有的数据运行它?
答案 0 :(得分:1)
从Jinja 2 documentation调整,可能就像
一样简单>>> template = Template(report.markup)
>>> template.render(report=report)
<html>...
如果要将输出存储到另一个变量
>>> final_markup = template.render(report=report)
前提是您的模板希望将整个报告作为report
模板参数。