How to add pagination to django comments for your model

First step is
import Comment and ContentType to your view like below

from django.contrib.comments.models import Comment
from django.contrib.contenttypes.models import ContentType

Second step is defining your model which you want to paginate its comments
content_type_id=
ContentType.objects.get_for_model(YOUR_MODEL_NAME)

Last
get comments of specific instance of your model class with defining object_pk as filter parameter
comments = Comment.objects.filter(content_type=content_type_id,object_pk=quote_id)

here is complete view code

from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.contrib.comments.models import Comment
from django.contrib.contenttypes.models import ContentType
def quote_show_page(request,quote_id):
quote = get_object_or_404(Quote, id=quote_id)
content_type_id=ContentType.objects.get_for_model(Quote)
comments = Comment.objects.filter(content_type=content_type_id,object_pk=quote_id)
paginator = Paginator(comments, 5) # Show 5 comments per page

# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1

# If page request (9999) is out of range, deliver last page of results.
try:
comments = paginator.page(page)
except (EmptyPage, InvalidPage):
comments = paginator.page(paginator.num_pages)


variables = RequestContext(request, {
'quote':quote,
'comments':comments
})
return render_to_response('quoteshow.html', variables)


add following lines to your template
{% for comment in comments.object_list %}
<lu>
<hr>
<li>{{comment.user}} dedi ki: </li>
<br>
{{comment.comment}}
({{comment.submit_date}})
<br>
</lu>
{% endfor %}
<br>
<div class="pagination">
<span class="step-links">
{% if comments.has_previous %}
<a href="?page={{ comments.previous_page_number }}">previous</a>
{% endif %}

<span class="current">
Page {{ comments.number }} of {{ comments.paginator.num_pages }}.
</span>

{% if comments.has_next %}
<a href="?page={{ comments.next_page_number }}">next</a>
{% endif %}
</span>
</div>

Comments

Popular posts from this blog

Pyppeteer fix for BrowserError: Browser closed unexpectedly

overlay filesystem and containers