From 445196c2d8461106976d3a16f5e38b7633bc5e71 Mon Sep 17 00:00:00 2001 From: cawal Date: Mon, 9 Aug 2021 14:35:14 -0300 Subject: [PATCH] Django: fixes pagination parameter When a user pass the `p` parameter in query, Django returns a string. The string needs to be casted to integer in order to be used in the paginator. Otherwise, the response returns BadRequest. --- restless/dj.py | 6 ++++-- tests/test_dj.py | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/restless/dj.py b/restless/dj.py index 2d7a0fc..8a8165d 100644 --- a/restless/dj.py +++ b/restless/dj.py @@ -27,8 +27,10 @@ def serialize_list(self, data): if getattr(self, 'paginate', False): page_size = getattr(self, 'page_size', getattr(settings, 'RESTLESS_PAGE_SIZE', 10)) paginator = Paginator(data, page_size) - - page_number = self.request.GET.get('p', 1) + try: + page_number = int(self.request.GET.get('p', 1)) + except ValueError: + raise BadRequest('Invalid page number') if page_number not in paginator.page_range: raise BadRequest('Invalid page number') diff --git a/tests/test_dj.py b/tests/test_dj.py index 520d712..f1b5855 100644 --- a/tests/test_dj.py +++ b/tests/test_dj.py @@ -279,6 +279,14 @@ def test_as_list_paginated_invalid_page(self): self.assertEqual(resp['Content-Type'], 'application/json') self.assertEqual(resp.status_code, 400) + def test_as_list_paginated_page_number_is_not_integer(self): + list_endpoint = DjTestResourcePaginated().as_list() + req = FakeHttpRequest('GET', get_request={'p': 'string'}) + + resp = list_endpoint(req) + self.assertEqual(resp['Content-Type'], 'application/json') + self.assertEqual(resp.status_code, 400) + def test_as_detail(self): detail_endpoint = DjTestResource.as_detail() req = FakeHttpRequest('GET')