I am trying to create a calendar with events showing under the date if and event has been created in the Event
model along with a DateTimeField
.
Here's my code: views.py
from django.shortcuts import render
import calendar
from .models import Event
def Cal(request, year, month):
calendar.setfirstweekday(calendar.SUNDAY)
prev_year = int(year)
next_year = int(year)
prev_month = int(month) - 1
next_month = int(month) + 1
if prev_month == 0:
prev_year -= 1
prev_month = 12
if next_month == 13:
next_year += 1
next_month = 1
month_cal = calendar.monthcalendar(int(year), int(month))
events = Event.objects.filter(when__year=year, when__month=month)
return render(request, "cal/calendar.html", {
"month_cal": month_cal,
"prev_month": prev_month,
"next_month": next_month,
"prev_year": prev_year,
"next_year": next_year,
"events": events,
})
calendar.html
{% extends "base.html" %}
{% block body %}
<table border="1" cellspacing="0" cellpadding="10" width="40%" height="80%">
<tr>
<td>Sun</td>
<td>Mon</td>
<td>Tue</td>
<td>Wed</td>
<td>Thu</td>
<td>Fri</td>
<td>Sat</td>
</tr>
{% for week in month_cal %}
<tr>
{% for day in week %}
<td>
{% if day == 0 %}
-
{% else %}
{{ day }}
{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<a href="{% url 'calendar:calendar' prev_year prev_month %}">previous</a>
<a href="{% url 'calendar:calendar' next_year next_month %}">next</a>
{% endblock %}
I am successfully able to loop through all the events and loop through all the dates in the calendar. But, I want the events to be displayed inside the calendar under appropriate dates.