I'm learning Python and Django and am building a job management app, I have the following, which is all working ok, and displays the jobs on a HTML calendar. It displays the start and end dates okay, however if the job is more than two days there is a gap in the calendar as there is no date related to the job to show.
I can get the dates in between by doing the following;
start = job.start_time
end = job.end_time
between = end - start
for i in range(between.days + 1):
datesbetween = [start + timedelta(days=i)]
Below is my views.py file:
class AdminCalendarView(LoginRequiredMixin,PermissionRequiredMixin, ListView):
model = Job
template_name = 'jobs/admin_diary.html'
permission_required = 'jobs.add_job', 'raise_exception=True'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# use today's date for the calendar
d = get_date(self.request.GET.get('month', None))
# Instantiate our calendar class with today's year and date
cal = AdminCalendar(d.year, d.month)
jobs = Job.objects.filter(start_time__year=d.year, start_time__month=d.month)
# Call the formatmonth method, which returns our calendar as a table
html_cal = cal.formatmonth(jobs, withyear=True)
context['calendar'] = mark_safe(html_cal)
context['prev_month'] = prev_month(d)
context['next_month'] = next_month(d)
return context
The utils.py file:
from datetime import datetime, timedelta, date
from calendar import HTMLCalendar
from .models import Job
from django.db.models import Q
class AdminCalendar(HTMLCalendar):
def __init__(self, year=None, month=None):
self.year = year
self.month = month
super(AdminCalendar, self).__init__()
# formats a day as a td
# filter jobs by day
def formatday(self, day, jobs):
jobs_per_day = jobs.filter(Q(start_time__day=day) | Q(end_time__day=day))
d = ''
for job in jobs_per_day:
d += f"<a href='/job/{job.id}'> <li class='job-diary'> {job.client} Job: {job.id}</li> </a>"
if day != 0:
return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>"
return '<td></td>'
# formats a week as a tr
def formatweek(self, theweek, jobs):
week = ''
i = [a_tuple[0] for a_tuple in theweek]
for d in i:
week += self.formatday(d, jobs)
return f'<tr> {week} </tr>'
# formats a month as a table
# filter jobs by year and month
def formatmonth(self, jobs, withyear=True):
cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar table-responsive">
'
cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}
'
cal += f'{self.formatweekheader()}
'
for week in self.monthdays2calendar(self.year, self.month):
cal += f'{self.formatweek(week, jobs)}
'
cal += f'</table>'
return cal
However, I'm not sure how I need to approach passing these days back into the formatday() method, or if I should be looking at a different way of doing it, as it all new to me, any help would be much appreciated.
Thanks