0

In the classs based view I can just go "paginate_by = 8" and in html I can do

{% if page_obj.has_previous %}
     <a class="btn btn-outline-info mb-4" href="?page=1">First</a>
     <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}

But for function based view, is there anything I can do such as paginate_by such that I don't have to modify my html from what I have?

1 Answer 1

1

Yes, you can implement the pagination [Django-doc] yourself, like:

from app.models import SomeModel
from django.core.paginator import Paginator
from django.http import Http404
from django.shortcuts import render

def some_view(request):
    paginate_by = 8
    qs = SomeModel.objects.all()
    page = request.GET.get('page') or 1
    try:
        page = int(page)
    except ValueError:
        raise Http404('Invalid page number')
    paginator = Paginator(qs, paginate_by)
    try:
        page = paginator.page(page)
    except InvalidPage as e:
        raise Http404('Invalid page number')
    return render(
        request,
        'some_template.html',
        {'page_obj': page, 'object_list': page.object_list}
    )

We here thus use a Paginator [Django-doc] object to paginate the queryset.

This is more or less what a MultipleObjectMixin does to paginate the result. But the above actually already to some extent shows that for such views, you better use a class-based view, such that you can remove the boilerplate code.

Sign up to request clarification or add additional context in comments.

1 Comment

not sure if you'll reach but do you have an experience with django-notification-hq? I read the documentation multiple time but still don't know why notification won't be read from unread........notification works but it stays unread even when it's already been read

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.