Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Custom 404 Error when resource not found in Django Rest Framework

I am learning Django Rest Framework, and also new to django. I want to return a custom 404 error in json when a client will access a resource which was not found.

My urls.py looks liks this:

urlpatterns = [
    url(r'^mailer/$', views.Mailer.as_view(), name='send-email-to-admin')
]

In which i have only one resource, which can be accessed through URI, http://localhost:8000/mailer/

Now, when a client access any other URI like http://localhost:8000/, API should return a 404-Not Found error like this:

{
    "status_code" : 404
    "error" : "The resource was not found"
}

Please suggest some answer with proper code snippets, if suitable.

like image 410
Akshay Pratap Singh Avatar asked Jul 13 '15 09:07

Akshay Pratap Singh


People also ask

How do I return a 404 response in Django?

The Http404 exceptionIf you raise Http404 at any point in a view function, Django will catch it and return the standard error page for your application, along with an HTTP error code 404. In order to show customized HTML when Django returns a 404, you can create an HTML template named 404.

How do I create a custom exception in Django REST framework?

You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.

How do I show 404 in Django?

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.


2 Answers

You are looking for handler404.

Here is my suggestion:

  1. Create a view that should be called if none of the URL patterns match.
  2. Add handler404 = path.to.your.view to your root URLconf.

Here is how it's done:

  1. project.views

    from django.http import JsonResponse
    
    
    def custom404(request, exception=None):
        return JsonResponse({
            'status_code': 404,
            'error': 'The resource was not found'
        })
    
  2. project.urls

    from project.views import custom404
    
    
    handler404 = custom404
    

Read error handling for more details.

Django REST framework exceptions may be useful as well.

like image 61
Ernest Ten Avatar answered Sep 16 '22 18:09

Ernest Ten


according to django documentation : Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL. ref: https://docs.djangoproject.com/en/1.8/topics/http/urls/

so you can just add another url in urlpatterns after the one you created and it should match all url patterns and send them to a view that return the 404 code.

i.e :

urlpatterns = [
url(r'^mailer/$', views.Mailer.as_view(), name='send-email-to-admin'),
url(r'^.*/$',views.Error404.as_view(),name='error404')]
like image 20
sabtikw Avatar answered Sep 18 '22 18:09

sabtikw