You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将月份数字转换为月份名称:Django项目中转换方案失效问题

解决Django中月份数字转名称的问题

嘿,我来帮你搞定这个月份名称显示的问题!你之前尝试了日期过滤器和Calendar工具没生效,大概率是因为没找对正确的使用姿势——毕竟你现在视图里传的是纯数字的月份,直接用过滤器肯定不行,得先把它转换成可处理的对象,或者在视图里提前生成月份名称。下面给你两种靠谱的解决方法:

方法1:在视图中构造日期对象,模板用date过滤器显示名称

这种方法更符合Django的惯用写法,利用内置的date过滤器来格式化月份:

首先修改你的views.py,构造一个当月的日期对象(比如当月第一天),并传递给模板:

from datetime import date
from django.template.response import TemplateResponse

def ticket(request, month, year):
    airline = Airline.objects.get(id=request.user.airline_id)
    # 修正:原来的timestamp变量未定义,应该是timestamps(filter返回QuerySet)
    timestamps = Timestamp.objects.filter(
        airline=airline,
        usage_on__year=year,
        usage_on__month=month
    )
    # 构造当月的日期对象
    usage_date = date(year, month, 1)
    return TemplateResponse(request, 'club/al_history.html', {
        'usage_date': usage_date,
        'usage_year': year,
        'timestamps': timestamps,
    })

然后在模板al.html中,用date过滤器格式化月份:

{% extends 'base.html' %}
{% block content %}
{# "F"表示完整月份名称(比如January),用"M"则是缩写(比如Jan) #}
<h3>{{ usage_date|date:"F" }}, {{ usage_year }}</h3>
{% endblock %}

方法2:在视图中用calendar模块直接生成月份名称

如果你更倾向于在后端处理好名称再传给模板,可以用Python内置的calendar模块:

修改views.py:

import calendar
from django.template.response import TemplateResponse

def ticket(request, month, year):
    airline = Airline.objects.get(id=request.user.airline_id)
    timestamps = Timestamp.objects.filter(
        airline=airline,
        usage_on__year=year,
        usage_on__month=month
    )
    # 获取完整月份名称,calendar.month_name的索引对应月份数字(1=January)
    month_name = calendar.month_name[month]
    # 若要缩写月份,改用calendar.month_abbr[month]
    return TemplateResponse(request, 'club/al_history.html', {
        'month_name': month_name,
        'usage_year': year,
        'timestamps': timestamps,
    })

模板里直接使用生成好的名称:

{% extends 'base.html' %}
{% block content %}
<h3>{{ month_name }}, {{ usage_year }}</h3>
{% endblock %}

另外提醒你一下,原来的视图代码里timestamp变量没有定义,应该是timestamps(因为filter()返回的是QuerySet集合),这个笔误要记得修正,不然模板渲染会报错哦!

内容的提问来源于stack exchange,提问作者user8817894

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:54:59