I have an app that paginates and show objects in a Django list view. I'm using paginate_by=20
in my list view.
When I have 20+ objects and Google indexes the second results page /results/?page=2
. Then when results go below 20 objects, this second page goes to 404.
What is the best way to redirect page 2 to /results/
when page 2, 3 etc don't return any results.
I thought about writing a custom 404 view to strip out the URL parameters, but I guess it's best to catch this in the list view itself?
Here's my ListView:
class ListingListView(ListView):
ORDER_BY_MAP = {
None: {
'directive': ListingsManager.CATEGORY_DEFAULT_ORDER,
},
'title': {
'label': 'Title A > Z',
'directive': ('title',),
},
'-title': {
'label': 'Title Z > A',
'directive': ('-title',),
},
'rating': {
'label': 'Rating',
'directive': ('-aggregate_rating', '-reviews_count'),
},
}
template_name = 'directory/listing_list.html'
context_object_name = 'listings'
paginate_by = 20
@cached_property
def country(self):
if 'country_slug' in self.kwargs:
country = get_object_or_404(Country, slug=self.kwargs['country_slug'])
set_user_language(self.request, country.language)
return country
else:
return None
@cached_property
def category(self):
if 'category_slug' in self.kwargs:
return get_object_or_404(Category.objects.select_related('parent').prefetch_related(
'children'), slug=self.kwargs['category_slug'])
else:
return None
@cached_property
def region(self):
if 'region_slug' in self.kwargs:
return get_object_or_404(Region, slug=self.kwargs['region_slug'])
else:
return None
def get_url_params(self):
return {k: v[0] for k, v in dict(self.request.GET).items()}
def get_queryset(self):
url_params = self.get_url_params()
user_order_by = url_params.get('order_by', None)
if user_order_by not in self.ORDER_BY_MAP:
user_order_by = None
country = self.country
category = self.category
region = self.region
queryset = Listing.objects.category_view(category, country, region)
return queryset.order_by(*self.ORDER_BY_MAP[user_order_by]['directive']).distinct()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
country = self.country
region = self.region
listings = self.get_queryset()
context['category'] = category = self.category
if region:
context['title'] = f'{category.name} in {region.name}'
else:
context['title'] = category.name
# Add information for the category sidebar
context['up_links'] = []
if not category.is_root:
root_category = Category.objects.root()
context['up_links'].append({
'name': root_category.name,
'link': reverse('directory-category', args=[country.slug, root_category.slug])
})
if category.parent:
context['up_links'].append({
'name': category.parent.name,
'link': reverse('directory-category', args=[country.slug, category.parent.slug])
})
if region:
context['up_links'].append({
'name': category.name,
'link': reverse('directory-category', args=[country.slug, category.slug])
})
if category.has_regions:
context['region_links'] = {}
regions = Region.objects.filter(listings__categories=category, listings__countries=country).order_by('name')
for item in regions:
context['region_links'][item.name] = reverse('directory-region',
args=[country.slug, category.slug, item.slug])
context['subcategories'] = []
if category.is_root:
children = Category.objects.filter(parent__isnull=True).exclude(is_root=True)
else:
children = category.children
for c in children.order_by('nav_menu_order'):
context['subcategories'].append({
'name': c.name,
'thumbnail_image': c.thumbnail_image,
'link': reverse('directory-category', args=[country.slug, c.slug]),
})
# Do not show recommended badge in root category view
context['show_recommended_badge'] = not category.is_root
# Add sorting menu
context['order_by_URLs'] = {}
for key, value in self.ORDER_BY_MAP.items():
if key:
context['order_by_URLs'][value['label']] = f'{self.request.path}?order_by={key}'
# Add total listings count (template only counts listings on that page, not total)
context['listings_count'] = listings.count()
# Add sorting parameters so we can preserve sorting in pagination links
url_params = self.request.GET.copy()
url_params.pop('page', None)
context['url_params'] = url_params
return context
What I ended up doing is writing a mixin that overrides the get
method. That way I can reuse this for all paginated ListViews without having to customise the paginator.
Here's the mixin:
class SafePaginateMixin(object):
def get(self, *args, **kwargs):
try:
return super().get(*args, **kwargs)
except Http404:
page = self.request.GET.get('page', None)
if page:
return redirect(self.request.path)
else:
raise
Then added the mixin to my ListView
:
class ListingListView(SafePaginateMixin, ListView)
If the 404 is raised by a URL with a page
URL parameter, then redirect to the request path. If not, raise the 404.