我已经构建了一个基本日历,它使用内置的calendar.Calendar函数生成一个包含当前月份的表(取自URL),但我想将事件附加到生成的日期。最好的方法是什么?
目前在我的观点中:
def view_calendar(request, year=None, month=None):
events = Event.objects.filter(creator=request.user)
new_event_form = EventForm()
now = datetime.date.today()
if year:
year = int(year)
else:
year = now.year
if month:
month = int(month)
else:
month = now.month
cal = calendar.Calendar(calendar.SUNDAY)
month_days = cal.monthdatescalendar(year, month)
args = {'events': events, 'month': month, 'year': year, 'month_days': month_days}
args.update(csrf(request))
args['new_event_form'] = new_event_form
return render(request, 'calendar.html', args)
在我的模板中,我可以像这样打电话给几周和几天:
<table cellpadding="3" width="100%">
<tr>
<td>Sunday</td>
<td>Monday</td>
<td>Tuesday</td>
<td>Wednesday</td>
<td>Thursday</td>
<td>Friday</td>
<td>Saturday</td>
</tr>
{% for week in month_days %}
<tr>
{% for day in week %}
<td>
{{day|date:"j"}}<br />
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
我喜欢做的是在我的观点中有这样的事情:
for week in month_days:
for day in week:
day['events'] = list(Event.objects.filter(creator=request.user, start_date=day))
但是我收到了这个错误: TypeError:'datetime.date'对象不支持项目分配
有没有办法可以轻松地将这些天转换为支持项目分配的对象,这样我就可以将事件附加到日期并将它们添加到日历中?
感谢并祝圣诞快乐,今天有人在计算。
答案 0 :(得分:0)
您不能使用日期类型对象,如dict。
day['events'] = xxx
相反,你可以做类似
的事情 events = [(day, Event.objects.filter(creator=request.user, start_date=day))
for day in [week for week in month_days]]
并在模板
中使用它 {% for week in events %}
<tr>
{% for day, events in week %}
<td>
{{day|date:"j"}}<br />
{% for event in events %}
{{ event }}<br/>
{% endfor %}
</td>
{% endfor %}
</tr>
{% endfor %}
答案 1 :(得分:0)
我根据delta32的建议开始工作。我需要创建一个空的Events字典,然后在遍历我的foor循环后将每个周附加到事件字典中。这让我:
events = []
for week in month_days:
week_events = [(day, TSEvent.objects.filter(created_by=request.user, date_start=day)) for day in week]
events.append(week_events)
然后,在日历模板中:
{% for week in events %}
<tr>
{% for day, events in week %}
<td>
<a href="/ts/calendar/{{day|date:"Y"}}/{{day|date:"m"}}/{{day|date:"j"|leading_zeros:"2"}}/">
{{day|date:"j"}}
</a>
<br />
{% for event in events %}
<p><a href="/apps/timesweet/events/{{event.id}}/"><b>{{event.name}}</b></a></p>
{% endfor %}
</td>
{% endfor %}
</tr>
{% endfor %}