How to get an associated model via a custom admin action in Django?

2024/10/13 20:13:57

Part 2 of this question asked and answered separately.

I have a Report and a ReportTemplate.

+----+----------+---------------+-------------+
| id |  title   |     data      | template_id |
+----+----------+---------------+-------------+
|  1 | report 1 | {data: [...]} |           1 |
+----+----------+---------------+-------------+reports table+----+-----------+---------------+------------+
| id |   title   |    markup     |    css     |
+----+-----------+---------------+------------+
|  1 | template1 | <doctype!>... | body {.... |
+----+-----------+---------------+------------+templates table

A Report belongs to a ReportTemplate. A ReportTemplate has many Report.

I have a custom admin action for Report in admin.py called 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):returnprint_as_pdf.short_description = 'Generate as pdf'

These are models:

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 3def __unicode__(self):return self.titleclass 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)

What I want to do is:

  1. retrieve the associated ReportTemplate and its markup field value
  2. put the data field value of the Report through the markup value in 1 which is written with jinja2 markup
  3. use weasyprint and print out the data-filled markup from 2 as pdf

I am stuck at step 1.

Given the parameters self, request, queryset, how do I retrieve the associated ReportTemplate and its markup field value?

UPDATE 1:

I tried this to test one of the answers given.

import logginglogger = logging.getLogger(__name__)# .... code here ...def print_as_pdf(self, request, queryset):for report in queryset:markup = report.template.markuplogger.debug(markup)return

UPDATE 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,},},
}

Wrote this in my settings.py

Generated a debug.log

However, contents of debug.log are empty

UPDATE 3:

needed to explicitly change

logger = logging.getLogger(__name__)

to

logger = logging.getLogger('reports.admin')
Answer

Just get the template field of your Report model:

def print_as_pdf(self, request, queryset):for report in queryset:markup = report.template.markup...
print_as_pdf.short_description = 'Generate as pdf'

UPDATE: To use the logger you should add these two lines at the beginning of the source file:

import logginglogger = logging.getLogger(__name__)
https://en.xdnf.cn/q/118039.html

Related Q&A

How can I use descriptors for non-static methods?

I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it refer…

psycopg2 not all arguments converted during string formatting

I am trying to use psycopg2 to insert a row into a table from a python list, but having trouble with the string formatting.The table has 4 columns of types (1043-varchar, 1114-timestamp, 1043-varchar, …

inherited function odoo python

i want to inherit function in module hr_holidays that calculate remaining leaves the function is :hr_holiday.py:def _get_remaining_days(self, cr, uid, ids, name, args, context=None):cr.execute("&…

ValueError in pipeline - featureHasher not working?

I think Im having issues getting my vectorizer working within a gridsearch pipeline:data as panda df x_train:bathrooms bedrooms price building_id manager_id 10 1.5 3 3000 53a5b119b…

pandas dataframe: meaning of .index

I am trying to understand the meaning of the output of the following code:import pandas as pdindex = [index1,index2,index3] columns = [col1,col2,col3] df = pd.DataFrame([[1,2,3],[1,2,3],[1,2,3]], index…

Extract text inside XML tags with in Python (while avoiding p tags)

Im working with the NYT corpus in Python and attempting to extract only whats located inside "full_text" class of every .xml article file. For example: <body.content><block class=&qu…

Python (Flask) and MQTT listening

Im currently trying to get my Python (Flask) webserver to display what my MQTT script is doing. The MQTT script, In essence, its subscribed to a topic and I would really like to categorize the info it …

I dont show the image in Tkinter

The image doesnt show in Tkinter. The same code work in a new window, but in my class it does not. What could be the problem ?import Tkinterroot = Tkinter.Tkclass InterfaceApp(root):def __init__(self,…

Read temperature with MAX31855 Thermocouple Sensor on Windows IoT

I am working on a Raspberry Pi 2 with Windows IoT. I want to connect the Raspberry Pi with a MAX31855 Thermocouple Sensor which I bought on Adafruit. Theres a Python libary available on GitHub to read …

PIP: How to Cascade Requirements Files and Use Private Indexes? [duplicate]

This question already has an answer here:Installing Packages from Multiple Servers from One or More Requirements File(1 answer)Closed 9 years ago.I am trying to deploy a Django app to Heroku where one …