Skip to content

Commit

Permalink
Django: fixes pagination parameter
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
cawal committed Dec 24, 2021
1 parent 49b579d commit 445196c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
6 changes: 4 additions & 2 deletions restless/dj.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
8 changes: 8 additions & 0 deletions tests/test_dj.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down

0 comments on commit 445196c

Please sign in to comment.