Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger a 500 error in Django?

Tags:

python

django

I'm trying to setup email error logging and I want to test it.

Whats an easy way to trigger a 500 error in Django? This surprisingly has not been discussed here yet.

like image 406
User Avatar asked Jul 09 '14 17:07

User


People also ask

What is server error 500 in Django?

When DEBUG is False , Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater). This gives the administrators immediate notification of any errors.

What is debug false in Django?

Open your settings.py file (or settings_local.py ) and set DEBUG = False (just add that line if necessary). Turning off the Django debug mode will: Suppress the verbose Django error messages in favor of a standard 404 or 500 error page. You will now find Django error messages printed in your arches.


2 Answers

A test view like this will work:

from django.http import HttpResponse  def my_test_500_view(request):     # Return an "Internal Server Error" 500 response code.     return HttpResponse(status=500) 

or use the baked in error class:

from django.http import HttpResponseServerError def my_test_500_view(request):         # Return an "Internal Server Error" 500 response code.         return HttpResponseServerError() 
like image 60
agconti Avatar answered Oct 14 '22 08:10

agconti


Raising an appropriate Exception is the most robust way to test this. Returning an HttpResponse of any variety, as in @agconti 's answer, will not allow you to test the behavior of error handling. You'll just see a blank page. Raising an exception triggers both the correct response code and the internal Django behavior you expect with a "real" error.

Response code 500 represents the server not knowing what to do. The easiest way is to write into your test or test-view raise Exception('Make response code 500!').

Most other errors should be raised with exceptions designed to trigger specific response codes. Here's the complete list of Django exceptions that you might raise.

like image 34
Shaun Overton Avatar answered Oct 14 '22 10:10

Shaun Overton