首页 > 解决方案 > 如何从通用列表视图访问主键?

问题描述

我正在尝试从通用列表视图访问 url 的主键。让我解释。所以,我目前有一个简单的页面,其中包含来自模型的学生实例列表student。每一行都专用于一个学生,例如姓名、年龄、电子邮件等。现在,我想为每一行添加一个链接,以便单击后可以查看每个学生的日历。现在,日历视图是一个通用的 ListView,如下所示。

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

    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

但是,我希望日历仅显示与我点击的学生相关的信息。为此,我需要能够在我的日历视图中使用学生的主键(或 ID)。当然,我可以在 url 中嵌入主键,但我不知道如何访问我的 generic.ListView 中的 pk。另外,我知道你们中的一些人可能会建议我将视图切换为函数,但我不会使用函数,因为我使用通用版本进行了大部分编码。希望大家帮忙,有什么问题可以给我。

这是html模板:

<a href="{% url 'calendar' lead.pk %}" class="text-indigo-600 hover:text-indigo-900">
                                        Calendar
                                    </a>

这是网址:

path('personal/<int:pk>/calendar/', CalendarView.as_view(), name='calendar'),

标签: pythondjangodjango-modelsdjango-viewsdjango-templates

解决方案


假设您的 url 路径是这样的:

path('calendar/<int:studentId>/', CalendarView.as_view(), name='CalendarView'), 

然后你可以这样做:

class CalendarView(LoginRequiredMixin, generic.ListView):

    def get_queryset(self):
        return Class.objects.filter(student__id=self.kwargs['studentId'])

推荐阅读