2015-12-25 52 views
1

我已經構建了一個基本的日曆,它使用內置的calendar.Calendar函數生成當前月份的表格(取自URL),但我希望將事件附加到生成的日期。什麼是最好的方式來做到這一點?Django將事件附加到日曆中的日期?

目前在我的觀點:

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)) 

但我得到這個錯誤: 類型錯誤: 'datetime.date' 對象d oes不支持項目分配

有沒有一種方法可以輕鬆地將這些日子轉換爲支持項目分配的對象,以便我可以將Events添加到日曆中並將它們添加到日曆中?

謝謝,今天有計算機的人都有一個快樂的聖誕節。

回答

0

我得到它的工作基於關閉delta32的建議。我需要創建一個空的事件字典,然後在運行我的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 %} 
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 %} 
+0

我得到一個「類型錯誤:預期的字符串或緩衝區」從[一週特定行「爲每天500錯誤在month_days一週]你能給我更多的信息,這條線應該做什麼? –

+0

我得到它的工作基礎上你提供的答案,我將它添加爲下面的另一個答案。雖然,但我終於到了那裏! –