hebel.dev
hebel.dev

Reputation: 33

How can i get 'pk' or 'id' in get_context_data from ListView

How can i get 'pk' or 'id' in get_context_data from ListView

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'))

in output it gives empty queryset enter image description here

in urls

path('', views.AllListView.as_view(), name='all_products')
``

Upvotes: 1

Views: 2078

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

Your path has no pk URL parameter, so self.kwargs.get('pk') will be None, and thus not match an item.

You should encode the primary key in the URL, like:

path('<int:pk>/', views.AllListView.as_view(), name='all_products')

and in the ListView, you can then indeed retrieve the corresponding Collection:

from django.shortcuts import get_object_or_404

class AllListView(ListView):
    queryset = Product.objects.all()
    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()
        context['cool'] = get_object_or_404(Collection, pk=self.kwargs['pk'])
        return context

Upvotes: 3

Related Questions