1

Is there way to paginate another model in class based view in django? I have code like this. I would like to paginate comments is it possible?

class ShopDetailView(VisitCounter, DetailView):
    model = Item 
    template_name = 'shop/detail.html'
    context_object_name = 'item'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.filter(comment_item=self.object)
        context['form'] = CommentCreationForm()
        return context
Kay
  • 591
  • 1
  • 7
  • 27
  • Take a look into the below question :- https://stackoverflow.com/questions/5907575/how-do-i-use-pagination-with-django-class-based-generic-listviews – Shreeyansh Jain Oct 16 '21 at 03:40

1 Answers1

0

You can try below code, but with this approach you will need to refresh the detailview page every time to view old comments which is not code :-

def get_context_data(self, **kwargs):
    comments = Comment.objects.filter(comment_item=self.object)
    paginator = Paginator(comments, self.paginate_by)
    page = self.request.GET.get('page')
    try:
        comments = paginator.page(page)
    except PageNotAnInteger:
        comments = paginator.page(1)
    except EmptyPage:
        comments = paginator.page(paginator.num_pages)
        
    context['comments'] = comments
    return context

I Believe you should create separate view to render the comments and apply pagination on it and make ajax call to refresh the comment section whenever user click on next page.

Shreeyansh Jain
  • 1,407
  • 15
  • 25