I have a News
model that I want to put comments under. I know that I can send and use a list of comments to the template in DetailView via get_context_data
, but I want to have pagination for this list just like ListView
so that all comments aren’t loaded in the first step. Is there a way to do this?
Yes, but it’s going to involve some JavaScript - either directly or through some JS library or framework.
You’ll create a Django view that either returns the rendered page fragment containing the comments or just the comments themselves, perhaps in a JSON data structure.
When a portion of the comments are requested, the JavaScript will make an AJAX-style call to call that view, and then update the page with what the view returns.
Yes, I also wanted to implement infinite scroll with django-htmx
for the comments section, and I did it, but I don’t know how to do pagination in DetailView
so that it works properly.
First, “infinite scroll” doesn’t seem to be a proper “fit” along with pagination. I would think they perform two different functions.
Second, if you’re going to use pagination, you don’t do it in the DetailView. You handle that in the ListView that shows a page-worth’s of comments. If you have that ListView set up to return an HTML fragment, you could have your DetailView call the ListView to get the HTML, and allow the DetailView to add that to the page being rendered. (Or, if you want more uniform behavior in your code, you could not include any comments in the initial page rendering, and have the JavaScript load the first chunk of comments after the page has loaded.)
If you didn’t want to do any JavaScript interactivity, you could combine SingleObjectMixin
(for the News item) and ListView
(for the comments). Then you could use standard Django pagination with the ListView of comments.
See Using mixins with class-based views | Django documentation | Django