Part 2这个问题被单独提出并回答。
我有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
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):
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标记写的我被困在第1步。
根据参数self
,request
,queryset
,如何检索关联的ReportTemplate及其markup
字段值?
更新1:
我试过这个来测试给出的答案之一。
import logging
logger = logging.getLogger(__name__)
# .... code here ...
def print_as_pdf(self, request, queryset):
for report in queryset:
markup = report.template.markup
logger.debug(markup)
return
更新2:
# Logging
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/var/virtual/WebApps/virtualenvs/WeasyPrintProject/weasyprint_site/debug.log',
},
},
'loggers': {
'reports.admin': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
在我的settings.py
中写了这个生成一个debug.log
但是,debug.log的内容为空
更新3:
需要明确更改
logger = logging.getLogger(__name__)
到
logger = logging.getLogger('reports.admin')
答案 0 :(得分:1)
只需获取template
模型的Report
字段:
def print_as_pdf(self, request, queryset):
for report in queryset:
markup = report.template.markup
...
print_as_pdf.short_description = 'Generate as pdf'
更新:要use the logger,您应该在源文件的开头添加这两行:
import logging
logger = logging.getLogger(__name__)