python - 如何从通用列表视图访问主键?
问题描述
我正在尝试从通用列表视图访问 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'),
解决方案
假设您的 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'])
推荐阅读
- javascript - Wagtail:禁用管理员脏表单检查的首选方法
- postgresql - 我们可以在 postgresql 服务器的 Job Scheduling 中获取作业列表吗?
- tibco - 收到异常[尝试加载证书时:服务器证书无效]]
- r - R中的正则表达式提取两个匹配字符串之间的部分(不是意图)
- python - 熊猫扭曲 html 表格
- bash - 如何为名称在bash中的变量中的变量赋值?
- android - 如何销毁 CountdownTimer 的实例?
- python-3.x - 如何将 AWS 托管策略附加到 cloudformation 和对流层中的角色
- regex - 匹配 Perl 表达式的正则表达式?
- vector - 如何在不分配内存的情况下从 vec 中变异和删除元素?