Basic
Basic

Reputation: 26766

Disable Django exception formatting

I'm calling Django from within another application.

While debugging, if a Django exception occurs, the (html) response body is being picked up and then wrapped in an exception generated in the calling app.

This makes it a real pain to determine what the problem was as I need to wade through CSS, Html, Js, etc.

Is there any way to get Django to only output an exception message and a stack trace as plain text?

enter image description here

Upvotes: 1

Views: 1378

Answers (2)

Gareth Rees
Gareth Rees

Reputation: 65854

You can write your own exception-handling middleware class. See the documentation for the process_exception middleware method:

process_exception(self, request, exception)

request is an HttpRequest object. exception is an Exception object raised by the view function.

Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the response will be returned to the browser. Otherwise, default exception handling kicks in.

So I think you need to write something like this:

import traceback
from django.http import HttpResponse

class PlainTextExceptionMiddleware(object):
     def process_exception(self, request, exception):
         return HttpResponse(traceback.format_exc(), "text/plain")

and then add the class to your MIDDLEWARE_CLASSES setting.

Upvotes: 2

Igor
Igor

Reputation: 3179

Just set the DEBUG_PROPAGATE_EXCEPTIONS in your settings:

If set to True, Django’s normal exception handling of view functions
will be suppressed, and exceptions will propagate upwards. This 
can be useful for some test setups, and should never be used on a live site.

See the Django docs

Upvotes: 1

Related Questions