Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Django DetailView with pagination for related objects
# A DetailView of a User can have a paginated list of Purchases
# In the template, the pagination needs to done similar to the following example:
# {% bootstrap_pagination purchases_page_obj extra=request.GET.urlencode parameter_name="purchases_page" %}
from django.views.generic.detail import DetailView
from django.core import paginator
@method_decorator(staff_member_required(login_url='user_login'), name='dispatch')
class UserDetailView(DetailView):
model = User
template_name = "barsys/userarea/user_detail.html"
purchases_paginate_by = 5
def get_context_data(self, **kwargs):
context = super(UserDetailView, self).get_context_data(**kwargs)
purchases_page = self.request.GET.get("purchases_page")
purchases = self.object.get_purchases().filter()
purchases_paginator = paginator.Paginator(purchases, self.purchases_paginate_by)
# Catch invalid page numbers
try:
purchases_page_obj = purchases_paginator.page(purchases_page)
except (paginator.PageNotAnInteger, paginator.EmptyPage):
purchases_page_obj = purchases_paginator.page(1)
context["purchases_page_obj"] = purchases_page_obj
return context
@moustaphacheikh

This comment has been minimized.

Copy link

@moustaphacheikh moustaphacheikh commented Nov 27, 2018

MultipleObjectMixin

Hello, Thanks for sharing your code.
You can do this with less code using MultipleObjectMixin.
In the template (user_detail.html) you can access object_list and use pagination as you would in a ListView. In fact ListView uses MultipleObjectMixin.

from django.views.generic.detail import DetailView
from django.views.generic.list import MultipleObjectMixin

@method_decorator(staff_member_required(login_url='user_login'), name='dispatch')
class UserDetailView(DetailView,MultipleObjectMixin):
    model = User
    template_name = "barsys/userarea/user_detail.html"
    paginate_by = 5

    def get_context_data(self, **kwargs):
        object_list = self.object.get_purchases().filter()
        context = super(UserDetailView, self).get_context_data(object_list=object_list, **kwargs)
        return context
@vsonawala-guidance

This comment has been minimized.

Copy link

@vsonawala-guidance vsonawala-guidance commented Feb 18, 2020

How can I get next/prev link with this solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment