Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: ‘DoesNotExist’ object is not callable

Tags:

python

django

It's not always this code chunk but this is the most recent. It seems to be random, any thoughts?

try:
    u = User.objects.get(email__iexact=useremail)
except User.DoesNotExist:
    ...

Throws this error, randomly.

File "/srv/myapp/registration/models.py", line 23, in get_or_create_user
  u = User.objects.get(email__iexact=useremail)

File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 132, in get
  return self.get_query_set().get(*args, **kwargs)

File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 349, in get
  % self.model._meta.object_name)

TypeError: ‘DoesNotExist’ object is not callable
like image 784
Ryan Detzel Avatar asked Oct 24 '11 14:10

Ryan Detzel


People also ask

How do I fix TypeError list object is not callable?

The Python "TypeError: 'list' object is not callable" occurs when we try to call a list as a function using parenthesis () . To solve the error, make sure to use square brackets when accessing a list at a specific index, e.g. my_list[0] .

What does object is not callable mean in Python?

The “int object is not callable” error occurs when you declare a variable and name it with a built-in function name such as int() , sum() , max() , and others. The error also occurs when you don't specify an arithmetic operator while performing a mathematical operation.

Are lists callable?

list , being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list instances are not.


1 Answers

As Chris says in the comments above, your snippet is valid. Somewhere else in your code, you may be catching exceptions incorrectly.

You may have something like:

try:
    do_something()
except User.MultipleObjectsReturned, User.DoesNotExist:
    pass

instead of:

try:
    do_something()
except (User.MultipleObjectsReturned, User.DoesNotExist):
    pass

Without the parentheses, the except statement is equivalent to the following in Python 2.6+

except User.MultipleObjectsReturned as User.DoesNotExist:

The instance of the User.MultipleObjectsReturned exception overwrites User.DoesNotExist.

When the same process handles a different request later on, you get the TypeError because your code is trying to call the exception instance which has replaced User.DoesNotExist.

like image 195
Alasdair Avatar answered Oct 19 '22 12:10

Alasdair