需要在函数

时间:2017-02-14 15:15:41

标签: python html django function

我正在使用django Web框架,需要在views.py中的函数中访问用户名。我只需根据数据是属于用户还是其他人来分配一个类。

因此请求视图是独立的,所讨论的视图仅用于呈现日历。如下:

@login_required
def holiday(request):
    #i want this later on
    user = request.user

    #some stuff to make the calendar
    cal = HolidayCalendar(my_holidays).formatmonth(year, month)

    # more stuff 

    context = {
        "calendar": mark_safe(cal),
    }
    return render(request, "tande/calendar.html", context)

这是我在

中访问用户所需的HTML日历
class HolidayCalendar(HTMLCalendar):

    def __init__(self, holiday):
        super(HolidayCalendar, self).__init__()
        self.holiday = self.holiday_days(holiday)

    def formatday(self, day, weekday, user):
        #do some stuff...
        if holiday_object:
            # links to holiday object
            body.append('<a href="%s"><center>' % holiday_object.get_absolute_url())
            body.append(esc(holiday_object.person_id))
            body.append('</center></a>')

            # I NEED THE USER HERE
            if holiday_object.person_id == user:
                body.append('<hr class="holiday">')
            else:
                #want to have a different hr class

而且我不知道如何将用户传递给此功能....我尝试了会话但是在没有请求的情况下也没有工作。

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

最简单的方法就是将用户传递给类初始化器。

def __init__(self, holiday, user):
    super(HolidayCalendar, self).__init__()
    self.user = user
    self.holiday = self.holiday_days(holiday)

def formatday(self, day, weekday):
    ...
    if holiday_object.person_id == self.user:

并在您看来:

cal = HolidayCalendar(my_holidays, request.user).formatmonth(year, month)