Skip to content

Instantly share code, notes, and snippets.

@gpichot
Last active December 12, 2018 12:36
Show Gist options
  • Save gpichot/043e7549d7cbdb058a545a6b4f81cd09 to your computer and use it in GitHub Desktop.
Save gpichot/043e7549d7cbdb058a545a6b4f81cd09 to your computer and use it in GitHub Desktop.
Add error codes in django rest framework for form validation
from rest_framework.views import exception_handler
from rest_framework.exceptions import ErrorDetail, _get_full_details
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status'] = response.status_code
if response.status_code == 400:
for key, value in response.data.items():
try:
response.data[key] = _get_full_details(response.data[key])
except:
pass
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment