How do I import the Django DoesNotExist exception?

BryanWheelock picture BryanWheelock · Jun 19, 2012 · Viewed 69.2k times · Source

I'm trying to create a UnitTest to verify that an object has been deleted.

from django.utils import unittest
def test_z_Kallie_can_delete_discussion_response(self):
  ...snip...
  self._driver.get("http://localhost:8000/questions/3/want-a-discussion") 
  self.assertRaises(Answer.DoesNotExist, Answer.objects.get(body__exact = '<p>User can reply to discussion.</p>'))

I keep getting the error:

DoesNotExist: Answer matching query does not exist.

Answer

Chris Pratt picture Chris Pratt · Jun 19, 2012

You can also import ObjectDoesNotExist from django.core.exceptions, if you want a generic, model-independent way to catch the exception:

from django.core.exceptions import ObjectDoesNotExist

try:
    SomeModel.objects.get(pk=1)
except ObjectDoesNotExist:
    print 'Does Not Exist!'