[Django]-Show request.DATA in Django 500 error caused by Rest Framework

5👍

There is a version which works for Django 1.9+ and Rest Framework 3.4

from rest_framework import permissions
from rest_framework.views import exception_handler


def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is None and context['request'].method not in permissions.SAFE_METHODS:
        context['request']._request.POST = context['request'].data

return response

4👍

In settings.py :

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'core.exceptions.exception_handler',
}

The handler:

def exception_handler(exc, drf_request=None):
    """
    Replace request.POST with drf_request.DATA so Sentry
    can log request properly.

    @param exc: Exception
    @param drf_request: Request
    @return: None
    """
    response = views.exception_handler(exc)
    if response is None and drf_request is not None \
            and drf_request.method not in ['GET', 'HEAD', 'OPTIONS']:
        request = get_request()
        request.POST = drf_request.DATA

    return response

Leave a comment