I am trying to paginate get_context_data from views.py, by selecting from among multiple context objects. Only two choices are shown in the code example conditional statements, but I have several more choices which basically cover all choices from the form submission. Only one context is returned, in the end however, passing the context to the template view for pagination.
I tried also setting pagination globally in settings.py, but it is not working.
I have viewed the article below, previously, as a guide to pagination on get-context-objects.
How to perform pagination for context object in django?
From views.py:
from django.shortcuts import render
import django.views.generic
from django.http import HttpResponse
from django.template import loader
from django.template import RequestContext
from ephemera.models import *
from ephemera.serializers import ItemSerializer
from rest_framework import generics
from ephemera.forms import SearchForm, AdvSearchForm
from itertools import chain
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
class SearchResultsAdvancedView(django.views.generic.ListView):
template_name = 'ephemera/searchresults_advanced.html'
form = AdvSearchForm()
paginate_by = 10
model = Item
def get_context_data(self, **kwargs):
context = super(SearchResultsAdvancedView, self).get_context_data(**kwargs)
choose_collection = self.request.GET.get('choose_collection')
user_input = self.request.GET.get('user_input')
choose_item = self.request.GET.get('choose_item')
bookpage = False
imagepage = False
if choose_collection == 'All' and user_input == '' and choose_item == 'book':
context['book_qs'] = Item.objects.raw('SELECT * FROM ephemera_item WHERE ephemera_item.material_type LIKE %s', ['book']);
bookpage = True
elif choose_collection == 'All' and user_input == '' and choose_item == 'image':
context['image_qs'] = Item.objects.raw('SELECT * FROM ephemera_item WHERE ephemera_item.material_type LIKE %s', ['image']);
imagepage = True
if bookpage:
paginator = Paginator(context, self.paginate_by)
page = self.request.GET.get('page')
try:
book_qs = paginator.page(page)
except PageNotAnInteger:
book_qs = paginator.page(1)
except EmptyPage:
book_qs = paginator.page(paginator.num_pages)
context['book_qs'] = book_qs
elif imagepage:
paginator = Paginator(context, self.paginate_by)
page = self.request.GET.get('page')
try:
image_qs = paginator.page(page)
except PageNotAnInteger:
image_qs = paginator.page(1)
except EmptyPage:
image_qs = paginator.page(paginator.num_pages)
context['image_qs'] = image_qs
return context
Errors returned include:
Exception Value: unhashable type: 'slice'
Exception Location: c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\django\core\paginator.py in page, line 70