Reportlab: dynamic color for table column (color saved in django model) in reportlab

I have a django model called TestResults

models.py

Class TestResults(models) chemical_name charfield value floatfield unit charfield method charfield normal_limit charfield caution_limit charfield color charfield 

Now,

The code below will generate a table for oils that has the following fields.

views.py

  fields = ('Test Name', 'Value', 'Unit', 'Method', 'Normal Limit', 'Caution Limit') all_oils = [(test.chemical_name, test.value, test.unit, test.method, test.normal_limit, test.caution_limit) for test in TestResult.objects.all())] oil_table = Table([fields] + all_oils oil_table.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, 0), '#a7a5a5'), ('FONTSIZE', (0, 0), (-1, 0), 6), ('GRID', (0, 0), (-1, -1), 2, '#a7a5a5'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('FONTNAME',(1,1),(1,-1),'Times-Bold')])) 

Now, how can I provide a dynamic color for each column. Suppose my TestResult model has a field for color (I, e color = red)

In the report, I need a dynamic color for the second column that comes from model objects

How can i achieve this?

+4
source share
1 answer

Maybe something is missing for me, but it seems very easy.

In your objects, save the color you want in a variable, such as color , as a valid ReportLab color specification (for example, a string with a hexadecimal color value). Then, when you create your report, if you want to set the background color, just set it for all the cells in the column. For example, to set the background of column x , add the following to your TableStyle :

 ('BACKGROUND', (x, 0), (x, -1), anObject.color) 

TableStyle can add as many 'BACKGROUND' styles to 'BACKGROUND' that you can do this for each column that you want to change color.

+1
source

Source: https://habr.com/ru/post/1381538/


All Articles