django写一个日历,包含日历图形模板和views代码
时间: 2024-02-03 10:13:45 浏览: 289
日历图形模板 calendar.html:
```html
{% extends "base.html" %}
{% block content %}
<h2>{{ month_name }} {{ year }}</h2>
<table>
<thead>
<tr>
<th>周日</th>
<th>周一</th>
<th>周二</th>
<th>周三</th>
<th>周四</th>
<th>周五</th>
<th>周六</th>
</tr>
</thead>
<tbody>
{% for week in weeks %}
<tr>
{% for day in week %}
{% if day %}
<td>
<a href="{% url 'event_detail' day.year day.month day.day %}">
{{ day.day }}
{% for event in day.events %}
<br>{{ event.title }}
{% endfor %}
</a>
</td>
{% else %}
<td></td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
```
views.py代码:
```python
from django.shortcuts import render, get_object_or_404, redirect
from django.utils.safestring import mark_safe
from django.urls import reverse
from datetime import datetime, timedelta
from calendar import HTMLCalendar
from .models import Event
class Calendar(HTMLCalendar):
def __init__(self, events):
super(Calendar, self).__init__()
self.events = events
def formatday(self, day, weekday):
if day != 0:
cssclass = self.cssclasses[weekday]
if datetime.now().date() == datetime(self.year, self.month, day).date():
cssclass += ' today'
if datetime.now().date() > datetime(self.year, self.month, day).date():
cssclass += ' past'
if datetime.now().date() < datetime(self.year, self.month, day).date():
cssclass += ' future'
events_per_day = self.events.filter(start_time__day=day)
d = ''
for event in events_per_day:
d += f'<li> {event.get_html_url} </li>'
if d != '':
return f"<td class='{cssclass}'><span class='date'>{day}</span><ul> {d} </ul></td>"
return f"<td class='{cssclass}'><span class='date'>{day}</span></td>"
return '<td></td>'
def formatweek(self, theweek):
week = ''
for d, weekday in theweek:
week += self.formatday(d, weekday)
return f'<tr> {week} </tr>'
def formatmonth(self, year, month):
self.year, self.month = year, month
events = Event.objects.filter(start_time__year=year, start_time__month=month)
cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n'
cal += f'{self.formatmonthname(year, month, withyear=True)}\n'
cal += f'{self.formatweekheader()}\n'
for week in self.monthdays2calendar(year, month):
cal += f'{self.formatweek(week)}\n'
cal += f'</table>'
return mark_safe(cal)
def calendar_view(request, year, month):
events = Event.objects.filter(start_time__year=year, start_time__month=month)
cal = Calendar(events).formatmonth(int(year), int(month))
return render(request, 'calendar.html', {'calendar': cal, 'month_name': datetime.strptime(str(month), '%m').strftime('%B'), 'year': year, 'weeks': events})
def event_detail(request, year, month, day):
event = get_object_or_404(Event, start_time__year=year, start_time__month=month, start_time__day=day)
context = {'event': event}
return render(request, 'event_detail.html', context)
```
阅读全文