Following the MongoDB tutorial (http://django-mongodb-engine.readthedocs.org/en/latest/tutorial.html), I have a model called Post in an app called 'tutorial.' I have the app, along with djangotoolbox, installed:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'djangotoolbox',
'tutorial'
)
I have the following connection settings with a name, user, and password that is set up on MongoLab:
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': '*****',
'USER': '*****',
'PASSWORD': '******',
'HOST': 'ds047720.mongolab.com',
'PORT': '47720'
}
}
When I SSH into my host, I can run manage.py validate and I get "0 errors found." When I go into the shell and follow the tutorial to create a new Post, this is what happens:
(InteractiveConsole)
>>> from tutorial.models import Post
>>> post = Post.objects.create(
... title='123',
... text='test',
... tags=['a','b']
... )
Traceback (most recent call last):
File "<console>", line 4, in <module>
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/manager.py", line 149, in create
return self.get_query_set().create(**kwargs)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/query.py", line 416, in create
obj.save(force_insert=True, using=self.db)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/base.py", line 548, in save
force_update=force_update, update_fields=update_fields)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/base.py", line 668, in save_base
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/manager.py", line 215, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/query.py", line 1675, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py", line 592, in execute_sql
key = self.insert(to_insert, return_id=return_id)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/compiler.py", line 84, in wrapper
return func(*args, **kwargs)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/compiler.py", line 387, in insert
collection = self.get_collection()
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/compiler.py", line 296, in get_collection
return self.connection.get_collection(self.query.get_meta().db_table)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/base.py", line 196, in get_collection
collection = self.collection_class(self.database, name, **kwargs)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/base.py", line 204, in __getattr__
self._connect()
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/base.py", line 261, in _connect
self.connection = connection_class(**conn_options)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/pymongo/mongo_client.py", line 369, in __init__
raise ConnectionFailure(str(e))
DatabaseError: timed out
>>>
Obviously, Django is having a difficult time connecting to the database, but I'm able to connect just fine using Mongo Management Studio. I've read similar tutorials here: http://compsocsci.blogspot.com/2012/02/getting-started-with-django-heroku-and.html
and here:
http://dennisgurnick.com/2010/07/06/bootstrapping-a-django-with-mongo-project/
but I have no idea what's stopping django from connecting to my database. Has anyone overcome a similar issue with the mongodb engine? Does anyone know what I'm missing?
Related
I created my first with MongoDB with Django
while during the setup I am getting this problem error
Internal Server Error: /api/v1/device/
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 856, in parse
return handler(self, statement)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 928, in _insert
query.execute()
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 397, in execute
res = self.db[self.left_table].insert_many(docs, ordered=False)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/collection.py", line 761, in insert_many
blk.execute(write_concern, session=session)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 528, in execute
return self.execute_command(generator, write_concern, session)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 363, in execute_command
_raise_bulk_write_error(full_result)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 140, in _raise_bulk_write_error
raise BulkWriteError(full_result)
pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: farmos.device index: __primary_key__ dup key: { id: null }', 'keyPattern': {'id': 1}, 'keyValue': {'id': None}, 'op': {'device_id': 2, 'device_name': None, 'device_status': 'new', 'device_actions': True, 'device_token': True, '_id': ObjectId('63182c4ee9afd58ca7855029')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []}
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 56, in execute
params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 783, in __init__
self._query = self.parse()
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 868, in parse
raise exe from e
djongo.exceptions.SQLDecodeError:
Keyword: None
Sub SQL: None
FAILED SQL: INSERT INTO "device" ("device_id", "device_name", "device_status", "device_actions", "device_token") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s)
Params: [2, None, 'new', True, True]
Version: 1.3.3
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 59, in execute
raise db_exe from e
djongo.database.DatabaseError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/adarsh/farmos/farmos/persistance_layer/mongodb/device_operations.py", line 22, in create
serializer_user.save()
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/query.py", line 433, in create
obj.save(force_insert=True, using=self.db)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 784, in save_base
force_update, using, update_fields,
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 926, in _do_insert
using=using, raw=raw,
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1391, in execute_sql
cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 59, in execute
raise db_exe from e
django.db.utils.DatabaseError
directory-path
farmos
/device -> model,view,serializer
/farm -> model,view,serializer
/persistances_layer -> model,view,serializer
/farmos -> settings.py, urls.py, utils.py
here Is my settings.py file
please let m know if there is any mistake that I am making here
"""
Django settings for farmos project.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-v-iu2x3pd&m0qap1k%y=8jua12v$adi*r132uha%&jdsp781(&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'device.apps.DeviceConfig',
'farm.apps.FarmConfig',
'persistance_layer.apps.PersistanceLayerConfig'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'farmos.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'farmos.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'farmos',
'CLIENT': {
'host': 'mongodb://srv13.absolute.ag:27017',
# 'username': 'user1',
# 'password': 'pass1',
# 'authSource': 'admin1',
# 'authMechanism': 'SCRAM-SHA-1',
}
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'COERCE_DECIMAL_TO_STRING': False,
# 'EXCEPTION_HANDLER': 'farmos.utils.custom_exception_handler',
}
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
here is the requirement.txt file packages that i am using
weasyprint~=52.5
boto3==1.10.41
django-3-jet==1.0.7
Django==3.2.4
django-cors-headers==3.7.0
django-extensions==2.2.3
django-filter==2.4.0
django-import-export==2.5.0
django-localflavor==2.2
django-phonenumber-field==3.0.1
django-rest-auth==0.9.5
django-simple-history==3.0.0
django-storages==1.8
djangorestframework==3.12.4
mysqlclient==2.0.3
phonenumbers==8.10.20
Pillow==8.2.0
requests==2.23.0
django-import-export==2.5.0
django-google-maps==0.12.4
drf-yasg==1.20.0
Flask==2.0.1
pandas==1.1.5
beautifulsoup4==4.9.3
slugify==0.0.1
django-taggit==1.3.0
PyMySQL==1.0.2
django-crontab==0.7.1
Werkzeug==2.0.2
numpy
python-dateutil==2.7.3
pytest==6.2.5
pytz==2019.3
jmespath==0.10.0
docutils==0.15.2
lxml==4.7.1
cffi==1.15.0
future==0.18.2
ipython==7.16.3
olefile==0.46
soupsieve==2.3.1
html5lib==1.1
httplib2==0.15.0
defusedxml==0.7.1
pip==21.3.1
keyring==18.0.1
PyYAML==5.3.1
Babel==2.9.1
botocore==1.13.50
s3transfer==0.2.1
MarkupSafe==2.0.1
Jinja2==3.0.3
click==8.0.3
blinker==1.4
itsdangerous==2.0.1
setuptools==45.2.0
sqlparse
asgiref==3.4.1
colorama==0.4.3
py==1.11.0
python-stdnum==1.17
tablib==3.1.0
xlrd==2.0.1
xlwt==1.3.0
MarkupPy==1.14
openpyxl==3.0.9
certifi==2019.11.28
chardet==3.0.4
itypes==1.2.0
coreapi==2.3.3
coreschema==0.0.4
uritemplate==4.1.1
cryptography==2.8
urllib3==1.25.8
simplejson==3.16.0
coverage==6.2
six==1.14.0
Pygments==2.10.0
inflection==0.5.1
idna==2.8
paramiko==2.6.0
pyparsing==3.0.6
google_api_python_client==2.42.0
oauth2client==4.1.3
ua-parser==0.10.0
user-agents==2.2.0
django-user-agents==0.4.0
django_db_logger
dataclasses==0.1
djongo==1.3.3
pymongo==3.11.2
djangotoolbox>=1.6.0
django-dbindexer>=1.6.0
gunicorn==19.9.0
django-crispy-forms==1.9.0
dnspython==1.16.0
For dealing with module named Djongo for connecting Django with MongoDb , one should be completely aware of the modules versions being used in the environment.
Make sure your using the library versions stated below.
asgiref==3.5.0,
Django==4.0.3,
djongo==1.3.6,
dnspython==2.2.1,
pykerberos==1.2.4,
pymongo==3.12.1,
python-snappy==0.6.1,
pytz==2022.1,
sqlparse==0.2.4,
configure the Database settings in the settings.py. Its not necessary to use host while connnecting to the localhost of MongoDb.
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your-db-name',
}
}
I have a simple Django app deployed to App Engine, which connects to Cloud SQL (PostgreSQL) instance. This Django app allows users to login/register and put up items for sale. Login/register works fine, but when putting up items for sale I get the following error:
Request Method: POST
Django Version: 3.0.3
Python Version: 3.7.7
Installed Applications:
['projects',
'blog',
'users.apps.UsersConfig',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/srv/projects/views.py", line 28, in createListing
link.save()
File "/srv/projects/models.py", line 24, in save
super(Listing_Database, self).save(*args, **kwargs)
File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 784, in save_base
force_update, using, update_fields,
File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_insert
using=using, raw=raw,
File "/env/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/env/lib/python3.7/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1383, in execute_sql
for sql, params in self.as_sql():
File "/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1328, in as_sql
for obj in self.query.objs
File "/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1328, in <listcomp>
for obj in self.query.objs
File "/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1327, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1278, in pre_save_val
return field.pre_save(obj, add=True)
File "/env/lib/python3.7/site-packages/django/db/models/fields/files.py", line 288, in pre_save
file.save(file.name, file.file, save=False)
File "/env/lib/python3.7/site-packages/django/db/models/fields/files.py", line 87, in save
self.name = self.storage.save(name, content, max_length=self.field.max_length)
File "/env/lib/python3.7/site-packages/django/core/files/storage.py", line 52, in save
return self._save(name, content)
File "/env/lib/python3.7/site-packages/django/core/files/storage.py", line 267, in _save
fd = os.open(full_path, self.OS_OPEN_FLAGS, 0o666)
Exception Type: OSError at /projects/createListing
Exception Value: [Errno 30] Read-only file system: '/srv/media/house_preview/question_4.PNG'
I'm pretty sure it's something to do with image upload.
Writing to Google App Engine instance is not allowed,
you should use Google Cloud Storage if you want everything in Google realm
Edit your code to support different Google cloud storage backend -> for example using django-storage
It not possible to write files in the Google App Engine Standard Python3 environment except in the /tmp directory. As stated in the Python3 GAE official documentation:
The runtime includes a full filesystem. The filesystem is read-only except for the location /tmp, which is a virtual disk storing data in your App Engine instance's RAM.
I am creating a app in django and I want to fetch data from mongolab.
But,I don't know how to connect mongolab to django.
I had connect mongodb to django but now I want to connect with mongolab.
How to do this?
I have used this in my setting.py file,
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'djangotoolbox',
'app'
)
And in DATABASE:,
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': '*****',
'USER': '*****',
'PASSWORD': '******',
'HOST': 'ds129469.mongolab.com',
'PORT': '26469'
}
}
And after running command, python manage.py runserver
I get following error,
life#life-All-Series:~/mongo/env1/project7/project$ python manage.py runrver
/home/life/.local/lib/python2.7/site-packages/djangotoolbox/db/utils.py:1: RemovedInDjango19Warning: The django.db.backends.util module has been renamed. Use django.db.backends.utils instead.
from django.db.backends.util import format_number
/home/life/.local/lib/python2.7/site-packages/djangotoolbox/db/utils.py:1: RemovedInDjango19Warning: The django.db.backends.util module has been renamed. Use django.db.backends.utils instead.
from django.db.backends.util import format_number
Performing system checks...
System check identified no issues (0 silenced).
Unhandled exception in thread started by <function wrapper at 0x7fbad4b24c08>
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/django/utils/autoreload.py", line 229, in wrapper
fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 116, in inner_run
self.check_migrations()
File "/usr/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 168, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 19, in __init__
self.loader = MigrationLoader(self.connection)
File "/usr/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 47, in __init__
self.build_graph()
File "/usr/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 191, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/usr/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 59, in applied_migrations
self.ensure_schema()
File "/usr/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 49, in ensure_schema
if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
File "/home/life/.local/lib/python2.7/site-packages/django_mongodb_engine/base.py", line 179, in table_names
return self.connection.database.collection_names()
File "/home/life/.local/lib/python2.7/site-packages/pymongo/database.py", line 488, in collection_names
ReadPreference.PRIMARY) as (sock_info, slave_okay):
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/home/life/.local/lib/python2.7/site-packages/pymongo/mongo_client.py", line 699, in _socket_for_reads
with self._get_socket(read_preference) as sock_info:
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/home/life/.local/lib/python2.7/site-packages/pymongo/mongo_client.py", line 663, in _get_socket
server = self._get_topology().select_server(selector)
File "/home/life/.local/lib/python2.7/site-packages/pymongo/topology.py", line 121, in select_server
address))
File "/home/life/.local/lib/python2.7/site-packages/pymongo/topology.py", line 97, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: ds129469.mongolab.com:29469: [Errno -2] Name or service not known
I am having problem with PyDev Unit Test when South is in my INSTALLED_APPS.
The error returned is: OperationalError: no such table: lists_list
If I comment South in INSTALLED_APPS or if I ran tests from shell with: python manage.py test, everything works fine.
Seems that there is a problem with creating test DB when running test from PyDev Unit Test and having South.
My environment is:
Win 8
Python 2.7
Eclipse Kepler Service Release 2
PyDev for Eclipse 3.8.0.201409251235
Django (1.6)
mock (1.0.1)
pytz (2014.7)
selenium (2.43.0)
South (1.0)
Here are the details:
settings.py
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'lists',
'south',
)
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
SOUTH_TESTS_MIGRATE = False # To disable migrations and use syncdb instead
SKIP_SOUTH_TESTS = True
tests.py
from django.test import TestCase
from lists.models import Item, List
class NewListTest(TestCase):
def test_saving_a_POST_request(self):
self.client.post(
'/lists/new',
data={'item_text': 'A new list item'}
)
self.assertEqual(Item.objects.count(), 1)
new_item = Item.objects.first()
self.assertEqual(new_item.text, 'A new list item')
Result:
Finding files... done.
Importing test modules ... done.
Creating test database for alias 'default'...
test_saving_a_POST_request (lists.tests.NewListTest) ... ERROR
======================================================================
ERROR: test_saving_a_POST_request (lists.tests.NewListTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\projects\learn\TDD_py2_dj16\superlists\lists\tests.py", line 30, in test_saving_a_POST_request
data={'item_text': 'A new list item'}
File "D:\virt_envs\django16test\lib\site-packages\django\test\client.py", line 483, in post
response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
File "D:\virt_envs\django16test\lib\site-packages\django\test\client.py", line 302, in post
return self.request(**r)
File "D:\virt_envs\django16test\lib\site-packages\django\test\client.py", line 444, in request
six.reraise(*exc_info)
File "D:\virt_envs\django16test\lib\site-packages\django\core\handlers\base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\projects\learn\TDD_py2_dj16\superlists\lists\views.py", line 14, in new_list
list_ = List.objects.create()
File "D:\virt_envs\django16test\lib\site-packages\django\db\models\manager.py", line 157, in create
return self.get_queryset().create(**kwargs)
File "D:\virt_envs\django16test\lib\site-packages\django\db\models\query.py", line 319, in create
obj.save(force_insert=True, using=self.db)
File "D:\virt_envs\django16test\lib\site-packages\django\db\models\base.py", line 545, in save
force_update=force_update, update_fields=update_fields)
File "D:\virt_envs\django16test\lib\site-packages\django\db\models\base.py", line 573, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "D:\virt_envs\django16test\lib\site-packages\django\db\models\base.py", line 654, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "D:\virt_envs\django16test\lib\site-packages\django\db\models\base.py", line 687, in _do_insert
using=using, raw=raw)
File "D:\virt_envs\django16test\lib\site-packages\django\db\models\manager.py", line 232, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "D:\virt_envs\django16test\lib\site-packages\django\db\models\query.py", line 1511, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "D:\virt_envs\django16test\lib\site-packages\django\db\models\sql\compiler.py", line 898, in execute_sql
cursor.execute(sql, params)
File "D:\virt_envs\django16test\lib\site-packages\django\db\backends\util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "D:\virt_envs\django16test\lib\site-packages\django\db\utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "D:\virt_envs\django16test\lib\site-packages\django\db\backends\util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "D:\virt_envs\django16test\lib\site-packages\django\db\backends\sqlite3\base.py", line 450, in execute
return Database.Cursor.execute(self, query, params)
OperationalError: no such table: lists_list
----------------------------------------------------------------------
Ran 1 test in 0.017s
FAILED (errors=1)
Destroying test database for alias 'default'...
Any ideas?
Any help would be appreciated.
I get django-nonrel, djangotoolbox and mongodbengine from github, and the setting.py is as following:
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'admin', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
)
ROOT_URLCONF = 'ptl.urls'
TEMPLATE_DIRS = ('/Users/bxshi/PycharmProjects/ptl/templates',)
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
)
Except that settings.py, I do not have any other .py file in my project.
The error I got is that:
BaoxuShis-MacBook:ptl bxshi$ python manage.py syncdb
Creating tables ...
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_manager(settings)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/Library/Python/2.7/site-packages/django/core/management/commands/syncdb.py", line 109, in handle_noargs
emit_post_sync_signal(created_models, verbosity, interactive, db)
File "/Library/Python/2.7/site-packages/django/core/management/sql.py", line 190, in emit_post_sync_signal
interactive=interactive, db=db)
File "/Library/Python/2.7/site-packages/django/dispatch/dispatcher.py", line 172, in send
response = receiver(signal=self, sender=sender, **named)
File "/Library/Python/2.7/site-packages/django/contrib/contenttypes/management.py", line 11, in update_contenttypes
content_types = list(ContentType.objects.filter(app_label=app.__name__.split('.')[-2]))
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 84, in __len__
self._result_cache.extend(self._iter)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 275, in iterator
for row in compiler.results_iter():
File "build/bdist.macosx-10.7-intel/egg/djangotoolbox/db/basecompiler.py", line 335, in results_iter
File "build/bdist.macosx-10.7-intel/egg/djangotoolbox/db/basecompiler.py", line 430, in build_query
File "build/bdist.macosx-10.7-intel/egg/django_mongodb_engine/compiler.py", line 160, in add_filters
File "build/bdist.macosx-10.7-intel/egg/django_mongodb_engine/compiler.py", line 168, in add_filters
ValueError: need more than 3 values to unpack
I find something related to this error about mongodbengine, a thread on BBS talk about that, but it says this is already fixed.
Simply use the official installation instructions on https://django-mongodb-engine.readthedocs.org/en/latest/topics/setup.html