3

When using Django REST Framework, the documentation mentions that the Http404 exception is intercepted and handled by DRF. However, when I try this in practice, I still get an HTML response from Django:

$ curl http://127.0.0.1:8000/foo
<h1>Not Found</h1><p>The requested URL /foo was not found on this server.</p>

Curiously, method-not-allowed exceptions are caught and turned into JSON correctly. Why isn't it working for 404s?

Edit: Appending -H 'Accept: application/json' also has no effect; the same HTML is still served.

4
  • Can you show the respective view ? Commented Jun 11, 2018 at 7:01
  • @JerinPeterGeorge There is no respective view, thus the 404. Commented Jun 11, 2018 at 7:02
  • Yes, you're not going to get a JSON or XML file as a response of HTTP 404. You don't need it either. Actually you don't even need an HTML file. The only thing you actually and really need are the HTTP headers. In your client you just have to check the HTTP status code. If it is 200, you can proceed, otherwise you have to handle an exception. Commented Jun 11, 2018 at 7:12
  • @cezar That's fine, but I'm still curious why the documentation says that DRF intercepts the Http404 exception. By that logic, 404s should also be turned into JSON-formatted errors, no? Commented Jun 11, 2018 at 7:46

1 Answer 1

3

I think this is simple logic that, the Method Not Allowed exception is related to a view which is defined using DRF. That means the exception raises when the request is reached at some view (DRF-View).

The Page Not Found exception raises at URL Dispatcher if the input URL is not matched with defined URLs and hence it calls the 404 (page not found) view . But also, DRF handles HTTP 404 Not Found when we try to get the details of an instance (api/some_endpoint/instance_id/) and it not found in DB

Reference: The 404 (page not found) view

Sign up to request clarification or add additional context in comments.

1 Comment

A ha, that explains it. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.