5

I would like to replace default django 404 (and other in the future) with the DRF response, as easy as it is possible, just to return (standard DRF response):

{
    "detail": "Not found."
}

So I put this code in my url.py file.

from rest_framework.exceptions import NotFound
from django.conf.urls import handler404
handler404 = NotFound

When I set Debug flag (in the set Ture I'm geting 500, when set it to False 404 but in the html form.

I've read doc here: http://www.django-rest-framework.org/api-guide/exceptions/ but to be honest I don't know how to put this into reality.

it seems to be easy, but somehow I failed to implement this (above code comes form the other SO threads).

Thank you in advance

Piotr
  • 77
  • 5

1 Answers1

2

You should create a custom view for the 404 then to use it. for example:

in views.py:

from django.http import HttpResponseNotFound
import json

def error404(request, exception):
    response_data = {}
    response_data['detail'] = 'Not found.'
    return HttpResponseNotFound(json.dumps(response_data), content_type="application/json")

then in urls.py:

from django.conf.urls import handler404

from yourapp.views import error404

handler404 = error404
Peter Sobhi
  • 2,542
  • 2
  • 22
  • 28
  • Hello, thank you for the quick replay, but behaviour is still the same ;( – Piotr Feb 16 '18 at 23:31
  • btw. main urls.py or the application one ? – Piotr Feb 16 '18 at 23:45
  • @Piotr please check the last edit. I have tried to make it using the DRF's implemented exception but didn't work. Also I added `exception` parameter to the handler function to bind with handler404 – Peter Sobhi Feb 17 '18 at 01:22
  • Hello Peter, thank you it's working now :) ! Anyway does it mean we can't use restframework exception ? What is good in the standard exceptions that there are translations provided. I don't know why, but when I try to do: response_data['detail'] = _('Not found.') I'm getting 500 again :( – Piotr Feb 18 '18 at 21:06
  • This works only on top `urls.py` file. To debug which file is the top you can here `.venv/lib/python3.7/site-packages/django/urls/resolvers.py@resolve_error_handler` – deathangel908 Mar 02 '20 at 11:19