Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import the Django DoesNotExist exception?

People also ask

How do I use exceptions in Django?

Django Exception Classes The base class for DoesNotExist exceptions. If a query does not return any result, this exception is raised. It raises when the requested field does not exist. This exception is raised by a query if only one object is expected, but multiple objects are returned.

Does not exist exception in Django?

The DoesNotExist exception is raised when an object is not found for the given parameters of a query. Django provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class with try/except.

How does Django handle connection error?

Use ifconfig to figure out the IP address that has been assigned to your virtual machine. Of course you could also use a different port instead of 8000 . Then use that address and port in your host browser to access your server.

What is integrity error in Django?

This means that your DB is expecting that field to have a value. So when it doesn't you get an error. null. If True, Django will store empty values as NULL in the database. Default is False.


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!'

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.


One thing to watch out for is that the second parameter to assertRaises needs to be a callable - not just a property. For instance, I had difficulties with this statement:

self.assertRaises(AP.DoesNotExist, self.fma.ap)

but this worked fine:

self.assertRaises(AP.DoesNotExist, lambda: self.fma.ap)

self.assertFalse(Answer.objects.filter(body__exact='<p>User...discussion.</p>').exists())