【发布时间】:2021-12-03 07:35:36
【问题描述】:
我正在尝试将用户信息传递给 utils.py,但不知道如何。这是我遇到问题的 utils.py 的一部分:
class Calendar(HTMLCalendar):
def formatmonth(self, withyear=True):
events = Class.objects.filter(date__year=self.year, date__month=self.month).exclude(student=None)
cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\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, events)}\n'
return cal
问题是查询集events。我想为它做如下的事情:
if self.request.user.is_student:
events = Class.objects.filter(date__year=self.year, date__month=self.month).exclude(student=None)
if self.request.user.is_teacher:
events = Class.objects.exclude(student=None)
基本上,我想根据使用网站的用户更改查询集。这就是为什么我需要在 utils.py 中使用 self.request.user 之类的东西。我尝试在views.py 中做def get_queryset(self),但它似乎不起作用。如果可能的话,我宁愿在我的views.py 中控制查询集,而不是我的utils.py。我希望你能帮忙,有任何问题都可以给我。
根据你们中的一些人的要求,这是我的观点:
class CalendarView(LoginRequiredMixin, generic.ListView):
model = Class
template_name = 'leads/calendar.html'
def get_queryset(self):
return Class.objects.filter(date=datetime.date(1111,11,11))
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 = Calendar(d.year, d.month)
# Call the formatmonth method, which returns our calendar as a table
html_cal = cal.formatmonth(withyear=True)
context['calendar'] = mark_safe(html_cal)
context['prev_month'] = prev_month(d)
context['next_month'] = next_month(d)
return context
def get_date(req_day):
if req_day:
year, month = (int(x) for x in req_day.split('-'))
return datetime.date(year, month, day=1)
return datetime.datetime.today()
...
如您所见,如果get_queryset 有效,我不需要做所有这些事情。
【问题讨论】:
-
你能看到请求中的用户对象吗?如果是,您可以看到 init 的值。
-
对不起,我不太明白你想让我做什么。你能澄清一下吗?
-
print(self.request.user) 在您的
formatmonth方法中并分享价值。 -
我明白了:
NameError: name 'request' is not defined -
打印(self.request.user)
标签: python django django-models django-views django-templates