Saša Kalaba
Saša Kalaba

Reputation: 4411

Django Rest Framework how to return detail not found on all invalid urls?

Django 1.7

DRF 3.3.2

Python 2.7

I want to return a 404 Response with {'detail': 'Not found'.} whenever I enter an invalid url.

However I get this only when I enter a valid url with invalid lookup parameters.

For example, if I make a GET request on:

http://127.0.0.1:8000/api/boxes/3e1659f3-9238-4b8f-a580-9b096d95bbfa/

i will get the requested object.

If I do the same thing with:

http://127.0.0.1:8000/api/boxes/3e1659f3-9238-4b8f-a580-9b096d95bbfajibbersihherelalalalalalala/

I will get a 404 with {'detail': 'Not found'.} message in the body.

If i try the same thing with this url:

http://127.0.0.1:8000/api/boxesevenbiggerjibberish

I will get a 404 with this error:

enter image description here

which will break my app.

So the question is, how do I set up my urls so that every invalid url is handled with the {'detail': 'Not found'.} message (which won't break my app).

UPDATE

The given answer will set a custom 404 view for your entire project (all aps).

If you want to set a custom 404 for a particular app inside a project, (e.g. you want your API to return json, but you want your app to return some custom template), then you can set a urlpattern to catch everything:

myapp/urls.py

urlpatterns = [
    ...,
    ...,
    url(r'^.*/$', views.error_page, name='error_page')
]

Make sure that the url is the last pattern (otherwise every url will call your custom error_page view).

Upvotes: 3

Views: 3276

Answers (1)

ilse2005
ilse2005

Reputation: 11429

You can write a custom 404 view and assign it to django's handler404. This could look like this (not tested):

urls.py

from django.conf.urls import handler404
from myapp import views

handler404 = views.error_page

views.py

from rest_framework.decorators import api_view
from rest_framework import status

@api_view()
def error_page(request):
    return Response({'detail': 'Not found'}, status=status.HTTP_404_NOT_FOUND)

Upvotes: 3

Related Questions