我如何从 ListView 中获取 'pk' 或 'id' in get_context_data
How can i get 'pk' or 'id' in get_context_data from ListView
如何从 ListView
中获取 get_context_data 中的 'pk' 或 'id'
class AllListView(ListView):
context_object_name = 'all_products'
queryset = Product.objects.all
template_name = 'jewelry_store/home.html'
def get_context_data(self,**kwargs):
context = super(AllListView,self).get_context_data(**kwargs)
context['collections'] = Collection.objects.all
context['products'] = self.queryset
context['cool'] = Collection.objects.filter(pk=self.kwargs.get('pk'))
在输出中它给出了空的查询集
在网址中
path('', views.AllListView.as_view(), name='all_products')
``
您的路径没有 pk
URL 参数,因此 self.kwargs.get('pk')
将是 None
,因此不匹配项目。
您应该在 URL 中对主键进行编码,例如:
path('<strong><int:pk></strong>/', views.AllListView.as_view(), name='all_products')
并且在 ListView
中,您确实可以检索到相应的 Collection
:
from django.shortcuts import get_object_or_404
class AllListView(ListView):
queryset = Product.objects.all<strong>()</strong>
template_name = 'jewelry_store/home.html'
context_object_name = 'products'
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['collections'] = Collection.objects.all<strong>()</strong>
context['cool'] = get_object_or_404(Collection, <strong>pk=self.kwargs['pk']</strong>)
return context
如何从 ListView
中获取 get_context_data 中的 'pk' 或 'id'class AllListView(ListView):
context_object_name = 'all_products'
queryset = Product.objects.all
template_name = 'jewelry_store/home.html'
def get_context_data(self,**kwargs):
context = super(AllListView,self).get_context_data(**kwargs)
context['collections'] = Collection.objects.all
context['products'] = self.queryset
context['cool'] = Collection.objects.filter(pk=self.kwargs.get('pk'))
在输出中它给出了空的查询集
在网址中
path('', views.AllListView.as_view(), name='all_products')
``
您的路径没有 pk
URL 参数,因此 self.kwargs.get('pk')
将是 None
,因此不匹配项目。
您应该在 URL 中对主键进行编码,例如:
path('<strong><int:pk></strong>/', views.AllListView.as_view(), name='all_products')
并且在 ListView
中,您确实可以检索到相应的 Collection
:
from django.shortcuts import get_object_or_404
class AllListView(ListView):
queryset = Product.objects.all<strong>()</strong>
template_name = 'jewelry_store/home.html'
context_object_name = 'products'
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['collections'] = Collection.objects.all<strong>()</strong>
context['cool'] = get_object_or_404(Collection, <strong>pk=self.kwargs['pk']</strong>)
return context