Search code examples
pythonhtmldjangocalendar

Python Django HTMLCalendar How To Set First Weekday To Sunday


Like title states goal is to get the weeks in the calendar to lead with Sunday as opposed to Monday like the below shows. I know calendar.setfirstweekday(calendar.SUNDAY) should be able to do the trick here. I just can't figure out how/where to add it in this code or if there's a different method needed. Won't waste your time with the dumb things I've tried to get Sunday to lead the week in the calendar.

enter image description here

Current Code That Displays Monday Week Start:

class Calendar(HTMLCalendar):
    def __init__(self, year=None, month=None, group=None):
        self.year = year
        self.month = month
        self.group = group
        super(Calendar, self).__init__()

    def formatday(self, day):
        d = ''
        if day != 0:
            return f"<td name='date-event-input' id={date(year=self.year, month=self.month, day=day)}><span " \
                   f"class='date'>{day}</span><ul>{d}</ul></td>"
        return '<td></td>'

    def formatweek(self, theweek):
        week = ''
        for d, weekday in theweek:
            week += self.formatday(d)

        return f'<tr> {week} </tr>'

    def formatmonth(self, withyear=True):
        cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar" id="calendar-table-id">\n'
        cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n'
        cal += f'{self.formatweekheader()}\n'
        for week in self.monthdays2calendar(self.year, self.month):
            cal += f'{self.formatweek(week)}\n'

        return cal

Appreciate any help


Solution

  • You can set it just after creating an instance of your custom calendar class. It should work. I mean;

    # Create an instance of your custom calendar class
    my_calendar = Calendar()
    
    
    # Set the first weekday to Sunday
    calendar.setfirstweekday(6)