Как передать информацию о пользователе в utils.py в django
Я пытаюсь передать информацию о пользователе в 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)
В принципе, я хочу менять набор запросов в зависимости от того, какой пользователь использует сайт. Поэтому мне нужно использовать что-то вроде self.request.user
в utils.py. Я пытался сделать def get_queryset(self)
в views.py, но, похоже, это не работает. Если это возможно, я бы хотел управлять набором запросов в моем 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
Как видите, если get_queryset
работает, мне не нужно делать все эти вещи.
Вы можете обновить метод querset как показано ниже, я полагаю, что дата - это поле datetime в классе вашей модели.
def get_queryset(self):
return self.model.objects.filter(date=datetime.datetime(2020,11,11))