How do I import the Django DoesNotExist exception? How do I import the Django DoesNotExist exception? django django

How do I import the Django DoesNotExist exception?


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 ObjectDoesNotExisttry:    SomeModel.objects.get(pk=1)except ObjectDoesNotExist:    print 'Does Not Exist!'


You don't need to import it - as you've already correctly written, DoesNotExist is a property of the model itself, in this case Answer.

Your problem is that you are calling the get method - which raises the exception - before it is passed to assertRaises. You need to separate the arguments from the callable, as described in the unittest documentation:

self.assertRaises(Answer.DoesNotExist, Answer.objects.get, body__exact='<p>User can reply to discussion.</p>')

or better:

with self.assertRaises(Answer.DoesNotExist):    Answer.objects.get(body__exact='<p>User can reply to discussion.</p>')


DoesNotExist is always a property of the model that does not exist. In this case it would be Answer.DoesNotExist.