mart1n
mart1n

Reputation: 6213

Django REST Framework does not intercept 404 exceptions and outputs HTML instead of JSON

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.

Upvotes: 3

Views: 547

Answers (1)

JPG
JPG

Reputation: 88519

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

Upvotes: 3

Related Questions