'Change renderer class inside custom pagination in django rest framework
I am using custom renderer class by default in settings.py. For api I check query parameter "page", if it exist then I paginate result else return normal response using default renderer class from settings.py. But I have problem, I want to use only JSONResponse renderer for pagination
settings.py
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'app.core.renderers.CustomJSONRenderer',
"rest_framework.renderers.JSONRenderer",
"rest_framework.renderers.BrowsableAPIRenderer",
),
}
renderers.py
class CustomJSONRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
status_code = renderer_context['response'].status_code
response = {
"success": True,
"message": None,
"data": data,
}
return super(CustomJSONRenderer, self).render(response, accepted_media_type, renderer_context)
views.py
class User_View(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = User_Serializer
pagination_class = CustomPagination
### If page param exist then use pagination class else not use
pagination.py
class CustomPagination(PageNumberPagination):
page_size_query_param = 'size'
page_size = int(settings.PAGE_SIZE)
def get_paginated_response(self, data):
return Response({
'success': True,
'total': self.page.paginator.count,
'page_size': self.get_page_size(self.request),
'current_page': self.page.number,
'last_page': self.page.paginator.num_pages,
'data': data,
})
wrong response:
{
"success": true,
"message": null,
"data": {
"success": true,
"total": 6,
"page_size": 15,
"current_page": 1,
"last_page": 1,
"data": [
{
"id": 1,
"username": "admin",
"permissions": []
}
]
}
}
Correct response (expected):
{
"success": true,
"total": 6,
"page_size": 15,
"current_page": 1,
"last_page": 1,
"data": [
{
"id": 1,
"username": "admin",
"permissions": []
}
]
}
How can I fix it?
Solution 1:[1]
I solve problem with updating CustomJSONRenderer class
class CustomJSONRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
status_code = renderer_context['response'].status_code
request = renderer_context.pop('request')
page = request.query_params.get('page', None)
# Check page query params
if page is not None:
response = data
else:
response = {
'success': True,
'message': None,
'data': data,
}
return super(CustomJSONRenderer, self).render(response, accepted_media_type, renderer_context)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Developer |