Reputation: 425
I am new to Django framework, I have used annotation to sum up all the Amounts paid in a specific month in a year. This is working fine but the problem is that am unable to convert the month int into a month name in the template
views.py
def income_report(request):
context = {}
if grab_data_passed == 'monthly':
daily_data=Income.objects.values('date__year', 'date__month')\
.annotate(amount=Sum('amount'))
context['daily_data']=daily_data
return render(request, 'reports/incomes_report_details.html', context)
template
{% for fo in daily_data %}
<tr>
<td>{{ fo.month }}</td>
<td>{{ fo.amount }}</td>
</tr>
{% endfor %}
How can change this annotated month into a month name in the templates. I know I have to first convert date__month back to month name in views before I pass it to the templates but how?
Upvotes: 0
Views: 164
Reputation: 234
You can create your own template filters like this in your case :
From django official documentation :
https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/
polls/
__init__.py
models.py
templatetags/
__init__.py
extra_filters.py
views.py
extra_filters.py :
from django import template
import calendar
register = template.Library()
...
@register.filter
def month_to_string(month):
return calendar.month_name[month]
and then in your template, first import extra_filters.py :
{% load extra_filters %}
...
...
{{ fo.month|month_to_string }}
Upvotes: 1