[Answered ]-Django class based views paginate_by as variable

2👍

You can add method get_paginate_by() to do what you need and use request from self.request.

The sample code would be

class CarListView(ListView):
  ...
  def get_paginate_by(queryset):
        user_settings = UserSettings.objects.get(user=self.request.user.id) 
        return user_settings.per_page

Handle the error conditions appropriately.

👤Rohan

0👍

In order to have a safe fallback:

class CarListView(ListView):
    model = models.Car      
    template_name = 'app/car_list.html'  
    context_object_name = "car_list"    
    paginate_by = 10
    user_settings = UserSettings


    def get_paginate_by(self, queryset):
        """
        Try to fetch pagination by user settings,
        If there is none fallback to the original.
        """

        try:
            self.paginate_by = self.user_settings.objects.get(user=self.request.user.id).per_page
        except:
            pass
        return self.paginate_by 

Or if you want to use this on different views, create a Mixin:

class UserPagination(object):

    def get_paginate_by(self, queryset):
        """
        Try to fetch pagination by user settings,
        If there is none fallback to the original.
        """
        try:
            self.paginate_by = self.user_settings.objects.get(user=self.request.user.id).per_page
        except:
            pass
        return self.paginate_by

Then:

class CarListView(UserPagination, ListView):
    model = models.Car      
    template_name = 'app/car_list.html'  
    context_object_name = "car_list"    
    paginate_by = 10
    user_settings = UserSettings

Leave a comment