【问题标题】:Building html calendar view using django使用 django 构建 html 日历视图
【发布时间】:2011-07-25 17:50:48
【问题描述】:

我正在尝试使用 django 构建一个日历视图,并试图避免在我的视图中写入任何 html 标签。我找到了一个帮助我到达那里的代码,

from datetime import date, datetime, timedelta, time
import calendar

year=2011
month=12
change=None

# init variables
cal = calendar.Calendar()
month_days = cal.itermonthdays(year, month)
lst = [[]]
week = 0

# make month lists containing list of days for each week
# each day tuple will contain list of entries and 'current' indicator
for day in month_days:
    lst[week].append((day))
    if len(lst[week]) == 7:
        lst.append([])
        week += 1

在我看来,我做了以下事情

<div class="calendar_panel_bottom_noborder">
    <span class="month">Juny 2011</span>
    <span class="day_name">S</span>
    <span class="day_name">M</span>
    <span class="day_name">T</span>
    <span class="day_name">W</span>
    <span class="day_name">T</span>
    <span class="day_name">F</span>
    <span class="day_name">S</span>
    {% for week in month_days %}

        {% for day in week %}
            <span class="date">{{ day }}</span>
        {% endfor %}

    {% endfor %}
    <div class="clear"></div>


</div>

现在,上面的代码正在根据月份和年份参数打印日历,但它们看起来是错误的。当我将它与日历进行比较时,使用 2011 年 12 月,该月的第一天从星期四开始,而在日历中,它从星期三开始。谁能帮忙指出我在这里做错了什么?

更新

问题似乎来自 itermonthdays。我尝试执行以下操作

>>> month_days = cal.itermonthdays(2011, 12)
>>> for day in month_days:
...  print day
... 
0
0
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
0

我不知道我是否应该更改某种设置或以不同的方式启动课程。但是,根据我的 PC 日历,输出应以 4 个零开头,以无结尾,它显示 2011 年 12 月从一周的第 5 天的星期四开始,因此在计数开始之前应该有 4 个零。嗯,对我如何解决这个问题有什么建议吗?

【问题讨论】:

  • 没有远程连接问题,但是你为什么用&lt;div&gt;&lt;span&gt;来表示表格数据?
  • 我有一个 CSS 类来处理表示。它显示输出一个表格,

标签: python django


【解决方案1】:

你需要包含

cal.setfirstweekday(6)

之前

monthdays = ...

根据python documentation,...

默认情况下,这些日历将星期一作为一周的第一天, 最后一个是星期日(欧洲大会)。

【讨论】:

  • 非常感谢。这正是我一直在寻找的:)
【解决方案2】:

在我看来,您的问题只是 itermonthdays 以星期一而不是星期日开头。您可以通过临时替换来确认这一点

itermonthdays

itermonthdates

lst[week].append(day)

lst[week].append(day.strftime("%A")))

这应该用星期几的名称临时替换天数。

编辑:解决问题的一种可能方法是将lst 初始化为[[0]],然后在循环结束时设置lst=lst[:-1]

【讨论】:

  • 我试过 itermonthdates(2011, 12) 但我的日期是从 11 月 28 日到 1 月 1 日。我不明白:S
  • 我注意到的东西总是少了一天。我测试了几个月
【解决方案3】:

当我将它与日历进行比较时,使用 2011 年 12 月,该月的第一天从星期四开始,而在日历中,它从星期三开始。谁能帮忙指出我在这里做错了什么?

我有坏消息要告诉你,2011 年 12 月的第一天是星期四,根据我的 windows 日历

【讨论】:

  • 代码显示,星期三是 12 月的第一天。它应该在星期四显示
猜你喜欢
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
相关资源
最近更新 更多