s_k s_k - 7 months ago 26
Python Question

TypeError at / 'SimpleLazyObject' object is not callable

I am trying to work on an old version of django with mongodb

Django==1.5.11
django-crispy-forms==1.5.2
django-ifc-rwfm==0.1
django-mongodb-engine==0.6.0
django-registration-redux==1.2
djangotoolbox==1.8.0
pymongo==3.2.2


I am trying to get connection to the database

but it returns : TypeError at /
'SimpleLazyObject' object is not callable


This is my __init__.py file

from django.conf import settings
from django.utils.functional import SimpleLazyObject

from pymongo import MongoClient

_connection = None


def get_connection():
global _connection
if not _connection:
_connection = MongoClient(
host=getattr(settings, 'MONGODB_HOST', None),
port=getattr(settings, 'MONGODB_PORT', None)
)
username = getattr(settings, 'MONGODB_USERNAME', None)
password = getattr(settings, 'MONGODB_PASSWORD', None)
db = _connection[settings.MONGODB_DATABASE]
if username and password:
db.authenticate(username, password)
return db
return _connection[settings.MONGODB_DATABASE]


MongoClient = SimpleLazyObject(get_connection)


def get_collection(collection_name):
return getattr(MongoClient, collection_name)




I am new to django, thanks in advance.

Answer

You have two things called MongoClient: the one you imported from pymongo, and the global class you assigned to a lazy object. But in get_connection, you are attempting to call the first of those, but by then the name has already been rebound to point to the second.

You should change that module-level name to something else.

(Note, none of this has anything to do with Django; it is a pure Python problem.)

Comments