Django cannot run tests when DATABASES 'default' is empty - python

I have some troubles running tests with setting DATABASES['default'] = {}.
I got the folowing error when running ./manage.py test
$ ./manage.py test --failfast
Creating test database for alias 'mydb'...
E
======================================================================
ERROR: test_admin (myapp.test.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 182, in __call__
self._pre_setup()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 754, in _pre_setup
self._fixture_setup()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 887, in _fixture_setup
if not connections_support_transactions():
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 874, in connections_support_transactions
for conn in connections.all())
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 874, in <genexpr>
for conn in connections.all())
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/utils/functional.py", line 55, in __get__
res = instance.__dict__[self.func.__name__] = self.func(instance)
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 782, in supports_transactions
self.connection.leave_transaction_management()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 338, in leave_transaction_management
if managed == self.get_autocommit():
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 345, in get_autocommit
self.ensure_connection()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 133, in ensure_connection
self.connect()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/utils.py", line 86, in __exit__
db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
AttributeError: 'DatabaseWrapper' object has no attribute 'Database'
----------------------------------------------------------------------
Ran 0 tests in 0.001s
FAILED (errors=1)
Destroying test database for alias 'mydb'...
settings.py
..
DATABASES = {
'default': {},
'mydb': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
}
DATABASE_ROUTERS = ['myapp.router.MyRouter']
router.py
class MyRouter:
def db_for_read(self, model, **hints):
return 'mydb'
def db_for_write(self, model, **hints):
return 'mydb'
def allow_migrate(self, db, model):
if db == 'default':
return False
return True
test.py
from django.test import TestCase
class MyTest(TestCase):
def test_admin(self):
self.assertEqual(1, 1)
I did some investigation and find that self.connect() was called on the dummy backend associated with 'default' alias. Since the dummy backend does not implement much fonctionnalities, the call fails. How can I run tests with DATABASES['default'] = {} ?

Use different settings.py files for production/development/testing (best).
And or use Sqlite as default entry (quickest).

Related

Django databases: problems with the test database

I am learning about Django testing.
I wrote a simple App with a simple model and would like to run tests to check the validity of a model method, but I get an error message when I run the test:
here's models.py
from django.db import models
class Trip(models.Model):
origin = models.CharField(max_length=20)
destination = models.CharField(max_length=20)
def __str__(self):
return self.origin
def is_valid(self):
return self.origin != self.destination
Here's test.py
from django.test import TestCase
from .models import Trip
# Create your tests here.
class TripModelTests(TestCase):
def test_trip(self):
a = Trip.objects.create(origin='a', destination='a')
self.assertIs(a.is_valid(), True)
here is settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'd57r9kcrhthdc7',
'USER': 'sdqxaruartlvrd',
'PASSWORD': 'e7b8f85611596ed125fe3ed4ea590f821f65e317c17ee7871be75b8130d72378',
'HOST': 'ec2-3-214-46-194.compute-1.amazonaws.com',
'PORT': '5432',
'TEST': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
}
and here is the error message i get when I run python manage.py test transport
Creating test database for alias 'default'...
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv
super().run_from_argv(argv)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 371, in execute
output = self.handle(*args, **options)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\test.py", line 53, in handle
failures = test_runner.run_tests(test_labels)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\test\runner.py", line 695, in run_tests
old_config = self.setup_databases(aliases=databases)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\test\runner.py", line 614, in setup_databases
return _setup_databases(
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\test\utils.py", line 170, in setup_databases
connection.creation.create_test_db(
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\creation.py", line 55, in create_test_db
self._create_test_db(verbosity, autoclobber, keepdb)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\creation.py", line 172, in _create_test_db
'dbname': self.connection.ops.quote_name(test_database_name),
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\postgresql\operations.py", line 113, in quote_name
if name.startswith('"') and name.endswith('"'):
AttributeError: 'WindowsPath' object has no attribute 'startswith'
The test works fine if I just use the default django settings and use a sqlite database....
The error could be due to your BASE_DIR path, in your settings.py, you need to remove the slash / and switch it over to the following
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
You may need to verify depending on your BASE_DIR contents that it points to the right place. One way to debugging this is to set ipdb() just after your database dictonary, so once you use python manage.py runserver, can can easily inspect the DATABASES structure.
import ipdb; ipdb.set_trace()
Source: https://pypi.org/project/ipdb/

Microsoft SQL Server 2008: Write to the server failed

I have a Django app with a worker process which does database transactions. Under the hood, I have an Azure SQL database attached to my application. The worker code looks something like this:
class Command(BaseCommand):
def handle(self, *args, **kwargs):
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
django.setup()
consumer = Consumer()
logging.info('Booting drive consumer')
while True:
messages = consumer.poll()
for message in messages:
...
DriveEvent.objects.create(event_id=response['Id'], drive_id=drive_payload['drive_id'])
...
After about 20 mins, the create db object calls start failing with the following error:
[drive-consumer-1]2017-07-19T03:19:08.545128400Z Traceback (most recent call last):
[drive-consumer-1]2017-07-19T03:19:08.545133000Z File "/code/miles/management/commands/drive_consumer_worker.py", line 28, in handle
[drive-consumer-1]2017-07-19T03:19:08.545137900Z drive_consumer.consume(json.loads(record.value))
[drive-consumer-1]2017-07-19T03:19:08.545142500Z File "/code/miles/workers/drive_consumer.py", line 35, in consume
[drive-consumer-1]2017-07-19T03:19:08.545152200Z self._on_create(message['calendar_id'], drive_payload, message['access_token'])
[drive-consumer-1]2017-07-19T03:19:08.545156900Z File "/code/miles/workers/drive_consumer.py", line 46, in _on_create
[drive-consumer-1]2017-07-19T03:19:08.545161500Z DriveEvent.objects.create(event_id=response['Id'], drive_id=drive_payload['drive_id'])
[drive-consumer-1]2017-07-19T03:19:08.545166500Z File "/usr/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
[drive-consumer-1]2017-07-19T03:19:08.545171300Z return getattr(self.get_queryset(), name)(*args, **kwargs)
[drive-consumer-1]2017-07-19T03:19:08.545175900Z File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 399, in create
[drive-consumer-1]2017-07-19T03:19:08.545180700Z obj.save(force_insert=True, using=self.db)
[drive-consumer-1]2017-07-19T03:19:08.545185400Z File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 796, in save
[drive-consumer-1]2017-07-19T03:19:08.545190200Z force_update=force_update, update_fields=update_fields)
[drive-consumer-1]2017-07-19T03:19:08.545194800Z File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 821, in save_base
[drive-consumer-1]2017-07-19T03:19:08.545211400Z with transaction.atomic(using=using, savepoint=False):
[drive-consumer-1]2017-07-19T03:19:08.545215800Z File "/usr/local/lib/python2.7/site-packages/django/db/transaction.py", line 184, in __enter__
[drive-consumer-1]2017-07-19T03:19:08.545220400Z connection.set_autocommit(False, force_begin_transaction_with_broken_autocommit=True)
[drive-consumer-1]2017-07-19T03:19:08.545224900Z File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 391, in set_autocommit
[drive-consumer-1]2017-07-19T03:19:08.545229600Z self._set_autocommit(autocommit)
[drive-consumer-1]2017-07-19T03:19:08.545234000Z File "/usr/local/lib/python2.7/site-packages/sql_server/pyodbc/base.py", line 453, in _set_autocommit
[drive-consumer-1]2017-07-19T03:19:08.545238600Z self.connection.autocommit = autocommit
[drive-consumer-1]2017-07-19T03:19:08.545243100Z File "/usr/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
[drive-consumer-1]2017-07-19T03:19:08.545247700Z six.reraise(dj_exc_type, dj_exc_value, traceback)
[drive-consumer-1]2017-07-19T03:19:08.545252200Z File "/usr/local/lib/python2.7/site-packages/sql_server/pyodbc/base.py", line 453, in _set_autocommit
[drive-consumer-1]2017-07-19T03:19:08.545256800Z self.connection.autocommit = autocommit
[drive-consumer-1]2017-07-19T03:19:08.545262600Z Error: ('08S01', '[08S01] [FreeTDS][SQL Server]Write to the server failed (20006) (SQLSetConnectAttr)')
Database init (in settings.py) looks something like this:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': os.environ.get('DB_NAME'),
'HOST': os.environ.get('DB_HOST'),
'PORT': '1433',
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'OPTIONS': {
'host_is_server': True,
'driver_supports_utf8': True,
'extra_params': 'tds_version=7.2;'
}
}
}
Per my experience, it seems to be caused by the tds_version that the 7.2 version does not support Azure SQL Database. Please refer to my answer for the other SO thread pymssql: Connection to the database only works sometimes to change to 7.3.
Possibly, the third-party project michiya/django-pyodbc-azure on GitHub may help for you to get the more details.
Hope it helps.

Django and read-only database connections

Assume a Django application which is supposed to use two MySQL databases:
default - for storing data represented by models A and B (read-write access)
support - for importing data represented by models C and D (read-only access)
The support database is a part of an external application and cannot be modified.
Since the Django application uses the built-in ORM for models A and B I figured it should use the very same ORM for models C and D, even though they map to tables in an external database (support.)
In order to achieve that I defined the models C and D as follows:
from django.db import models
class ExternalModel(models.Model):
class Meta:
managed = False
abstract = True
class ModelC(ExternalModel):
some_field = models.TextField(db_column='some_field')
class Meta(ExternalModel.Meta):
db_table = 'some_table_c'
class ModelD(ExternalModel):
some_other_field = models.TextField(db_column='some_other_field')
class Meta(ExternalModel.Meta):
db_table = 'some_table_d'
Then I defined a database router:
from myapp.myapp.models import ExternalModel
class DatabaseRouter(object):
def db_for_read(self, model, **hints):
if issubclass(model, ExternalModel):
return 'support'
return 'default'
def db_for_write(self, model, **hints):
if issubclass(model, ExternalModel):
return None
return 'default'
def allow_relation(self, obj1, obj2, **hints):
return (isinstance(obj1, ExternalModel) == isinstance(obj2, ExternalModel))
def allow_migrate(self, db, app_label, model_name=None, **hints):
return (db == 'default')
And finally adjusted settings.py:
# (...)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'resources', 'default.cnf'),
},
},
'support': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'resources', 'support.cnf'),
},
},
}
DATABASE_ROUTERS = ['myapp.database_router.DatabaseRouter']
# (...)
The user specified in support.conf for the support database has been assigned read-only privileges.
But when I run python manage.py makemigrations it fails with the following output:
Traceback (most recent call last):
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 112, in execute
return self.cursor.execute(query, args)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 226, in execute
self.errorhandler(self, exc, value)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorvalue
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute
res = self._query(query)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query
rowcount = self._do_query(q)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query
db.query(q)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query
_mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1142, "CREATE command denied to user 'somedbuser'#'somehost' for table 'django_migrations'")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 57, in ensure_schema
editor.create_model(self.Migration)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 295, in create_model
self.execute(sql, params or None)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 112, in execute
cursor.execute(sql, params)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 112, in execute
return self.cursor.execute(query, args)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 226, in execute
self.errorhandler(self, exc, value)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorvalue
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute
res = self._query(query)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query
rowcount = self._do_query(q)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query
db.query(q)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1142, "CREATE command denied to user 'somedbuser'#'somehost' for table 'django_migrations'")
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 100, in handle
loader.check_consistent_history(connection)
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/loader.py", line 276, in check_consistent_history
applied = recorder.applied_migrations()
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
self.ensure_schema()
File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 59, in ensure_schema
raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to user 'somedbuser'#'somehost' for table 'django_migrations'"))
It appears that Django tries to create the django_migrations table in the read-only database support nevertheless.
Is there any clean way to prevent the migrations mechanism from attempting that? Or do I have to employ another ORM library for this read-only access to the support database?
I encountered the same issue (using Django 1.11) and this question was at the top of my Google results for it.
Your initial solution is only missing one critical piece. You need to tell Django what database models 'C' and 'D' are using. What worked for me:
class ExternalModel(models.Model):
class Meta:
managed = False
abstract = True
app_label = 'support'
Then tell your database router how to behave when it encounters that app_label in the allow_migrate() section:
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == 'support':
return False
return (db == 'default')
I'm not sure that is the most-correct-solution in the eyes of the Django team, but effect is allow_migrate() returning False for any models defined with that app_label attribute value.
The Django documentation on routers doesn't mention this explicitly (or, at least with model code samples that make it clear how the ORM passes the value for 'db' to allow_migrate()), but between the 'app_label' and 'managed' attributes you can get it to work*.
* In my case the default is postgres and the read-only database is Oracle 12 via cx_Oracle.
It seems around the Django 1.10.1 timeframe, Tim Graham (the primary Django maintainer), accepted a patch that suppressed this specific exception but later withdrew the patch in favor of (roughly) the following method to work around this issue and to support read-only databases using the Django ORM.
Define a database router as described in the Django documentation
on routers I've attached an example router below that routes to a
different database based on an 'app' flag in the model meta.
In your routers allow_migrations method, return False for any db argument
that corresponds to a read-only database. This prevents the migration of
the model tables regardless of where they would be routed to.
This next part is a little weird but where the rubber hits the road and
actually answers the original question. To keep makemigrations from
attempting to create the django_migrations table in your read-only
database, the database traffic should not be routed. In the example
router, that means 'read_only' is not in DATABASE_APPS_MAPPING.
So, instead, Read-only databases are accessed explicitly with "using" (e.g. MyReadOnlyModel.objects.using('read_only').all()
Django database apps router
Had the same problem.
Django is trying to create the 'django_migrations' table in all DBs.
This happens even if there are no models associated with the read-only DB
and all routers are pointing a different DB.
I also ended up using peewee.

Using MongoDB as backend for Django: Error running "python manage.py migrate"

I am new to Django and wanted to use django with Mongodb as backend. I started with the examples given in the internet. but facing issues when i tried to run migrate.
Installed: django 1.8, pymongo 2.8, mongodb
Models.py
from __future__ import unicode_literal
from mongoengine import *
class Choice(EmbeddedDocument):
choice_text = StringField(max_length=200)
votes = IntField(default=0)
class Poll(Document):
question = StringField(max_length=200)
pub_date = DateTimeField(help_text='date published')
choices = ListField(EmbeddedDocumentField(Choice))
Setttings.py : Created a user "mango" in mongodb. mongodb was running fine
import mongoengine
from mongoengine import connect
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy',
},
}
SESSION_ENGINE = 'mongoengine.django.sessions'
_MONGODB_USER = 'mango'
_MONGODB_PASSWD = 'mango'
_MONGODB_HOST = 'localhost'
_MONGODB_NAME = 'performance'
_MONGODB_DATABASE_HOST = \
'mongodb://%s:%s#%s/%s' \
% (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)
mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
I tried to run python manage.py migrate, it was throwing the below error. But i am able to connect to Db from shell. Can someone of you please help me in understanding the problem?
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 302, in execute
settings.INSTALLED_APPS
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 99, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\pm348b\Desktop\Praneeth_Desktop\Python_Programs\TEST\mysite\mysite\settings.py", line 118, in <module>
mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
File "C:\Python27\lib\site-packages\mongoengine\connection.py", line 165, in connect
return get_connection(alias)
File "C:\Python27\lib\site-packages\mongoengine\connection.py", line 128, in get_connection
raise ConnectionError("Cannot connect to database %s :\n%s" % (alias, e))
mongoengine.connection.ConnectionError: Cannot connect to database default :
command SON([('saslStart', 1), ('mechanism', 'SCRAM-SHA-1'), ('autoAuthorize', 1), ('payload', Binary('n,,n=mango,r=OTc3NDkxNTE3NTM3', 0))]) on namespace performance.$cmd failed: Authentication failed.
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'Name of the Cluster',
'HOST': 'The link which mongo provides for python',
'USER': "Created User's username",
'PASSWORD': 'Password of the above user',
}
Use this in your settings.py file

AttributeError: 'Settings' object has no attribute 'DATABASE_ENGINE'

Im new to django and python, trying to run a piece of django code on my system but im running into these problems , im running version 2.7 python and v1.4 django
$ python manage.py runserver
Running in development mode.
Running in development mode.
Running in development mode.
Running in development mode.
Validating models...
HACKUING USER MODEL
Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x101981e50>>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 91, in inner_run
self.validate(display_num_errors=True)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 266, in validate
num_errors = get_validation_errors(s, app)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/validation.py", line 30, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/loading.py", line 158, in get_app_errors
self._populate()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/loading.py", line 64, in _populate
self.load_app(app_name, True)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/loading.py", line 88, in load_app
models = import_module('.models', app_name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/Kinnovate/Desktop/fsdjango/platformsite/notices/models.py", line 9, in <module>
from common.fields import PickleField
File "/Users/Kinnovate/Desktop/fsdjango/platformsite/common/fields/__init__.py", line 1, in <module>
from pickle import *
File "/Users/Kinnovate/Desktop/fsdjango/platformsite/common/fields/pickle.py", line 27, in <module>
mysql_backend = settings.DATABASE_ENGINE == 'mysql'
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 186, in inner
return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'DATABASE_ENGINE'
this is the part of settings.py relevant to the question
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(DIRNAME, 'database.sqlite3'), # 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.
}
}
how do i fix this?
What is /Users/Kinnovate/Desktop/fsdjango/platformsite/common/fields/pickle.py? Is it your code? Then you have an error in it, because you really don't have DATABASE_ENGINE in your seetings. Use settings.DATABASES['default']['ENGINE'] instead.
You are missing something
Because as your backtrace your database must be mysql.
File "/Users/Kinnovate/Desktop/fsdjango/platformsite/common/fields/pickle.py", line 27, in <module>
mysql_backend = settings.DATABASE_ENGINE == 'mysql'
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 186, in inner
return func(self._wrapped, *args)
Because its enter in mysql_backend = settings.DATABASE_ENGINE == 'mysql' line.
As per your settings its 'ENGINE': 'django.db.backends.sqlite3', so it must be enter in sqlite please check your app because it might be possible that your settings.py might be refer from another place.

Categories