【问题标题】:How to change annotated month int in a dictionary into a month name?如何将字典中带注释的月份 int 更改为月份名称?
【发布时间】:2020-03-03 09:09:05
【问题描述】:

我是 Django 框架的新手,我使用注释来总结一年中特定月份支付的所有金额。 这工作正常,但问题是无法将月份 int 转换为模板中的月份名称

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)

模板

  {% for fo in daily_data %}
         <tr>
           <td>{{ fo.month }}</td>
            <td>{{ fo.amount }}</td>
         </tr>
{% endfor %}

如何在模板中将此带注释的月份更改为月份名称。 我知道我必须先将 date__month 转换回视图中的月份名称,然后才能将其传递给模板,但是如何?

【问题讨论】:

标签: python django


【解决方案1】:

您可以根据自己的情况创建自己的模板过滤器:

来自 django 官方文档:

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]

然后在你的模板中,首先导入 extra_filters.py :

{% load extra_filters %}
...
...



{{ fo.month|month_to_string }}

【讨论】:

  • 收到此错误 过滤器无效:'month_to_string'
  • @MK Patel,上面的答案给了我解决问题的方法,现在可以去另一个模块了
  • @MUGOYADIHFAHSIH 他刚刚编辑了我的答案,使其更具可读性和更优化,只需查看 month_to_string 函数即可。
  • 是的,我只是优化了代码而已。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多