3👍
✅
If you need to change the default message, one way is to implement your own error handler like below:
#your_app/error_handler.py
def custom_exception_handler(exc, context):
....
# ovverride IsAuthenticated permission class exception
if(response.data['detail'].code == 'not_authenticated'):
response.data['code'] = Unauthorized.default_code
response.data['message'] = Unauthorized.default_detail
del response.data['detail']
return response
Also, don’t forget to add your own error handler in Django’s settings.py
REST_FRAMEWORK = {
"EXCEPTION_HANDLER": ("your_app.error_handler.custom_exception_handler")
}
Moreover, you can implement custom exception classes. For example:
class UnreadableCSVFile(APIException):
status_code = 400
default_detail = "Unable to read file."
default_code = "unreadable_csv_file"
0👍
For response with no exception
you can use a helper function. something like this.
def render_response(success, data=None, item=None, items=None, err_name=None,
err_message=None):
if success:
if data is not None:
return {
"success": True,
"data": data
}
elif item is not None:
return {
"success": True,
"data": {
"item": item
}
}
elif items is not None:
return {
"success": True,
"data": {
"items": items
}
}
else:
return {
"success": False,
"error": {
"name": err_name,
"message": err_message
}
}
and in your return statement for every response, use:
return Response(render_response(True, data=serializer.data), status= status.200_OK)
this will give
{
"success": true,
"data": {
...
}
}
and this can your standard format.
- [Django]-How do I add together fields from a manytomanyfield in django?
- [Django]-Initializing foreignkey in modelform
- [Django]-Mysqlclient install in python3 on mac os
- [Django]-Django Package tests not found
Source:stackexchange.com