Django: 500 conditional response depending on Accept header?

Django returns the default HTML error template when an unhandled exception occurs in the view. I would like to return a JSON response instead if the request had the header "Accept: 'application / json" (but otherwise, normal HTML was returned). How can i do this?

+4
source share
2 answers

You can specify your own 500 view function in which you should be able to modify the response accordingly. See https://docs.djangoproject.com/en/dev/topics/http/urls/#handler500

+1
source

Change handler500 handler in urls.py:

handler500 = 'application_name.views.error_500' 

Define a view function:

 def error_500(request): # check request header return HttpResponse( json.dumps(retval), mimetype='application/json') 
+2
source

Source: https://habr.com/ru/post/1396210/


All Articles