Django日历视图 - 如何传递URL

时间:2013-08-12 15:52:25

标签: python django calendar

我需要一个日历来显示时间表上的条目。我使用this guide来编写django日历,但它没有涵盖最后阶段,也就是说,实际上将url传递给视图并呈现日历。根据一个有根据的猜测出错,我的urlconf条目现在变成了这个怪物:

        url(r'^calendar/(?P<pk>\d+)/(?P<start__year>\d+)/(?P<start__month>\d+)/$', calendar(request, year, month)),

因此视图本身就是:

def calendar(request, year, month):
    my_timesheet = Timesheet.objects.order_by('start').filter(start__year=year, start__month=month)
    cal = TimesheetCalendar(my_timesheet).formatmonth(year, month)
    return render_to_response('calendar.html', {'calendar':mark_safe(cal),})

和日历生成是:

class TimesheetCalendar(HTMLCalendar):
    def __init__(self, Timesheet):
        super(TimesheetCalendar, self).__init__()
        self.Timesheet = self.group_by_day(Timesheet)

    def formatday(self, day, weekday):
        if day != 0:
            cssclass = self.cssclasses[weekday]
            if date.today() == date(self.year, self.month, day):
                cssclass += ' today'
            if day in self.Timesheet:
                cssclass += ' filled'
                body = ['<ul>']
                for timesheet in self.Timesheet[day]:
                    body.append('<li>')
                    body.append(esc(Timesheet.activity))
                    body.append('</li>')
                body.append('</ul>')
                return self.day_cell(cssclass, '%d %s' % (day, ''.join(body)))
            return self.day_cell(cssclass,day)
        return self.daycell('noday','&nbsp;')

    def formatmonth(self, year, month):
        self.year, self.month = year, month
        return super(TimesheetCalendar, self).formatmonth(year, month)

    def group_by_day(self, Timesheet):
        field = lambda Timesheet: Timesheet.start.day
        return dict(
            [(day, list(items)) for day, items in groupby(Timesheet, field)]
            )
    def day_cell(self, cssclass, body):
        return '<td class="%s">%s</td>' %(cssclass, body)

我必须做些什么才能从我的模型中的日期字段start正确传递这些属性月份和年份?

1 个答案:

答案 0 :(得分:1)

我认为url的第二个参数应该是表示函数的字符串或函数对象:

url(r'^calendar/(?P<pk>\d+)/(?P<start__year>\d+)/(?P<start__month>\d+)/$', calendar)

此外,当您在网址中使用命名组(例如。start__yearstart_month)时,它们将作为kwargs传递给您的视图函数而不是位置参数

def calendar(request, pk, start__year, start__month):
    pass