I am trying to render a pandas DataFrame to a Django template with some style options. My problem may be related to this issue: https://github.com/pandas-dev/pandas/issues/13140.
I have gone through these answers in stack overflow regarding this question:
Here is my models.py
class Fruit(models.Model):
fruit_name = models.CharField(max_length=20)
car_name = models.CharField(max_length=20)
week = models.DecimalField(max_digits=3, decimal_places=1, blank=True)
price = models.DecimalField(max_digits=3, decimal_places=1, blank=True)
def __str__(self):
return '%s & %s' % (self.fruit_name, self.car_name)
And views.py
def get_fruit(request, *args, **kwargs):
df = pd.DataFrame(list(Fruit.objects.all().values('fruit_name', 'car_name', 'week', 'price')))
df2 = df
cols = ['week', 'price']
df2[cols] = df2[cols].apply(pd.to_numeric, errors='coerce')
df3 = pd.pivot_table(df2, index='car_name', columns=['fruit_name', 'week'], values='price', fill_value='')
df3_index = df3.index
html = df2.style.applymap(color_red, subset=['price']).render()
df3_html = df3.style \
.applymap(color_red, subset=df3_index) \
.render()
context = {'html': html,
'df3_html': df3_html
}
return render(request, 'get_fruit.html', context)
def color_red(s):
color = 'red' if (-5.0 <= s >= 5.0) else 'black'
return 'color: %s' % color
get_fruit.html
{% extends "base.html" %}
{% block content %}
<h1> Table</h1>
{{ html | safe}}
<br>
<h1>Pivot table</h1>
{{ df3_html | safe }}
{% endblock %}
The template renders as:get_fruit webpage
As you can see from the above picture, df.style is working for my table (where values > 5 are red) but not for the pivot table. I am not sure if it's a bug or is it something in my code.
I am using Django: 2.0.6; Jinja2: 2.10; pandas: 0.23.1 and Python: 3.6.
I appreciate any help.