djangomany-to-manydetailview

Pagination a list of items inside a DetailView (many to many) Django


i have a model with a many-to-many relationship, i want print all items in that relationship from detailView with pagination (like 10 items for page) there is a way to get pagination automatic like in ListView?

class CardDetailView(DetailView):

    model = Card

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['banner'] = context['card'].banners.last()
        context['banner_slideshow'] = context['card'].banners.all().order_by('-created_on') #i need that list paginated
    
        return context

    def get_queryset(self):
        return Card.objects.all()

Solution

  • You can use a query parameter and then put the page query in the context

        page = request.GET.get('page', 1)
        paginator = Paginator(query_set_for_m2m, ITEMS_PER_PAGE)
        try:
            items = paginator.page(page)
        except Exception as e:
            items = paginator.page(1)
        context['m2m_list'] = items
    
    

    Put this code on your get_context_data, you can get the request from self.request as explained here