限制 utils.py 上的视图 - Django

Restrict view on utils.py - Django

我已经使用模板通过 Django 创建日历,但现在我不得不将此日历上的事件视图限制为仅创建事件的用户。

我没有这个日历的模型,只有事件,日历目前基于我的 util.py 文件:

utils.py

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

    # formats a day as a td
    # filter events by day
    def formatday(self, day, events):
        contracts_starting_per_day = events.filter(starting_date__day=day)
        contracts_ending_per_day = events.filter(ending_date__day=day)
        contracts_paying_per_day = events.filter(payment_date__day=day)
        d = ''


        for contract in contracts_starting_per_day:
            if contract.company_client:
                client = contract.company_client
            elif contract.person_client:
                client = contract.person_client
            else:
                client = '-'
            d += f"<a href='http://127.0.0.1:8000/contracts/editct/{contract.id}'> <li class='calendar-li starting' title='{contract.contract_name}'> {contract.contract_name} <p class='calendar-p'> {client} </p> </li> </a>"


        if day != 0:
            return f"<td class='calendar-td'><span class='date'>{day}</span><ul class='calendar-ul'> {d} </ul></td>"
        return "<td class='calendar-td'></td>"

    # formats a week as a tr
    def formatweek(self, theweek, events):
        week = ''
        for d, weekday in theweek:
            week += self.formatday(d, events)
        return f"<tr class='calendar-tr'> {week} </tr>"

    # formats a month as a table
    # filter events by year and month
    def formatmonth(self, withyear=True):
        contracts = Contract.objects.filter(starting_date__year=self.year, starting_date__month=self.month)

        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, contracts)}\n'
        return cal

views.py

class CalendarView(LoginRequiredMixin, generic.ListView):
    model = Contract
    template_name = 'calendar.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # Get the actual month to display the calendar
        d = get_date(self.request.GET.get('month', None))
        agenda = Calendar(d.year, d.month)
        html_agenda = agenda.formatmonth(withyear=True)
        #context['calendar'] = context['calendar'].filter(user=self.request.user)
        context['calendar'] = mark_safe(html_agenda)
        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 date(year, month, day=1)
    return datetime.today()


def prev_month(d):
    first = d.replace(day=1)
    prev_month = first - timedelta(days=1)
    month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)
    return month

def next_month(d):
    days_in_month = calendar.monthrange(d.year, d.month)[1]
    last = d.replace(day=days_in_month)
    next_month = last + timedelta(days=1)
    month = 'month=' + str(next_month.year) + '-' + str(next_month.month)
    return month

我已经 #context['calendar'] = context['calendar'].filter(user=self.request.user) 尝试了我的观点,但我遇到了这个错误:

KeyError at /agenda/calendar 'calendar'

只有当登录的用户和创建事件的用户相等时,是否有任何选项可以限制日历上的事件?

我也尝试过:

for contract in contracts_starting_per_day:
    if contract.user == request.user:

在我的日历实用程序上,但由于此实用程序未收到任何请求,因此无法使用它。

您正在尝试从上下文中检索 calendar,但它还不在上下文中。此行导致错误:

context['calendar'] = context['calendar'].filter(user=self.request.user)

您应该在视图的 get_queryset 方法中为您的模型定义查询集。该查询集可以在您在 context_object_name:

中设置的变量的上下文中访问
class CalendarView(...):
    ...
    context_object_name = 'contracts'
    def get_queryset(self):
        return Contract.objects.filter(user=self.request.user)

然后在模板中:

{% for contract in contracts %}
    {{ contract }}
{% endfor %}