Accessing specified database in migrate command django inside database router - django

Using Django 1.11, I am attempting to create a custom router to pick a database based on the URL that is used.
For instance, if the URL is customer1.example.com, I want to pick the database 'customer1', and similarly if it is customer2.example.com, I want it to pick the database 'customer2'
My current setup works great! One problem - when I try to run migrations (or other database dependent commands), then it fails - even if I specify the database using the --database option, such as python manage.py migrate --database customer1
I'm not sure what to do, as there is no request for those - I want to actually return the exact name specified in the command line (such as customer1). But it isn't in hints, or any of the other options. How do I access the command line option that was used to run the command? Otherwise I have nothing to return!
This is my setup:
settings.py:
# Database to connect to
DATABASES = {
'default': {},
'customer1': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'xxxx',
'USER': 'yyyy',
'PASSWORD': 'zzzz',
'HOST': '192.168.168.176',
'PORT': '1521',
},
'customer2': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'xxxx',
'USER': 'yyyy',
'PASSWORD': 'zzzz',
'HOST': '192.168.168.179',
'PORT': '1521',
}
}
# Specify custom router
DATABASE_ROUTERS = ['workflow.router.RequestDatabaseRouter']
router.py (a custom router, uses a thread to get current request object)
from mainapp.threads import get_current_request
class RequestDatabaseRouter(object):
def db_for_read(self, model, **hints):
try:
request = get_current_request()
return request.META['HTTP_HOST'].split(':', 1)[0].split('.',1)[0]
except:
# ??????
def db_for_write(self, model, **hints):
try:
request = get_current_request()
return request.META['HTTP_HOST'].split(':', 1)[0].split('.',1)[0]
except:
# ??????
def allow_relation(self, obj1, obj2, **hints):
return True
def allow_migrate(self, db, app_label, model_name=None, **hints):
return True
I feel like something should be in the except block that just returns "whatever the --database option was in the command" - but I could not find a way to access that. Any advice?
Here is the output when I try to run the command: python manage.py migrate --database=customer1
Operations to perform:
Apply all migrations: MOC, admin, auth, contenttypes, frontend, sessions, sites, viewflow
Running migrations:
No migrations to apply.
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 227, in handle
self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan,
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal
**kwargs
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/dispatch/dispatcher.py", line 193, in send
for receiver in self._live_receivers(sender)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/dispatch/dispatcher.py", line 193, in <listcomp>
for receiver in self._live_receivers(sender)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/MOC/material/frontend/apps.py", line 158, in update_modules
_, created = DbModule.objects.get_or_create(label=module.label)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/query.py", line 464, in get_or_create
return self.get(**lookup), False
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/query.py", line 374, in get
num = len(clone)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/query.py", line 232, in __len__
self._fetch_all()
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/query.py", line 1118, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 876, in execute_sql
sql, params = self.as_sql()
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 428, in as_sql
extra_select, order_by, group_by = self.pre_sql_setup()
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 46, in pre_sql_setup
self.setup_query()
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 37, in setup_query
self.select, self.klass_info, self.annotation_col_map = self.get_select()
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 227, in get_select
sql, params = self.compile(col, select_format=True)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 373, in compile
sql, params = node.as_sql(self, self.connection)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/expressions.py", line 695, in as_sql
return "%s.%s" % (qn(self.alias), qn(self.target.column)), []
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 364, in quote_name_unless_alias
r = self.connection.ops.quote_name(name)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/db/backends/dummy/base.py", line 20, in complain
raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
The results of `manage.py migrate --database customer1:
{'customer1': {'PASSWORD': 'xxx', 'HOST': '192.168.168.176', 'NAME': 'mclaren', 'ENGINE': 'django.db.backends.oracle', 'PORT': '1521', 'USER': 'xxx'}, 'customer2': {'PASSWORD': 'xxx', 'HOST': '192.168.168.179', 'NAME': 'mclaren', 'ENGINE': 'django.db.backends.oracle', 'PORT': '1521', 'USER': 'xxx'}, 'default': {'PASSWORD': '', 'HOST': '', 'NAME': '', 'TIME_ZONE': None, 'USER': '', 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'PORT': '', 'TEST': {'CHARSET': None, 'MIRROR': None, 'NAME': None, 'COLLATION': None}, 'ENGINE': 'django.db.backends.dummy', 'ATOMIC_REQUESTS': False}}
The command still fails exactly as I described above. I've seen the default database get autopopulated while the site is running, but it seems to ignore whatever password I pass in. Maybe the router needs some adjustments, but I have no idea what to do with it.

Notice these lines in your stack trace:
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 227, in handle
self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan,
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal
**kwargs
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/dispatch/dispatcher.py", line 193, in send
for receiver in self._live_receivers(sender)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/lib/python3.5/site-packages/django/dispatch/dispatcher.py", line 193, in <listcomp>
for receiver in self._live_receivers(sender)
File "/mnt/c/cygwin64/home/chrisb/smart/python/MOC/MOC/material/frontend/apps.py", line 158, in update_modules
_, created = DbModule.objects.get_or_create(label=module.label)
Obviously, there is a post_migrate signal trying create a DbModule instance using the settings.DATBASE['default'] conf.
Which caused django.core.exceptions.ImproperlyConfigured.

Related

[FreeTDS][SQL Server]SQL Anywhere Error -265: Procedure 'SERVERPROPERTY' not found

I'm trying to connect to a SAP SQL Anywhere database with pyodbc and the FreeTDS ODBC driver.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'mssql_database': {
'ENGINE': 'django_pyodbc',
'NAME': 'blabla',
'USER': 'blabla',
'PASSWORD': 'blabla',
'HOST': '10.65.1.20',
'PORT': '1433',
'OPTIONS': {
'driver': 'FreeTDS',
'host_is_server': True,
},
},
'sybase_database': {
'ENGINE': 'django_pyodbc',
'NAME': 'blabla',
'USER': 'blabla',
'PASSWORD': 'blabla',
'HOST': '10.60.1.6',
'PORT': '2638',
'OPTIONS': {
'driver': 'FreeTDS',
'host_is_server': True,
},
},
}
Connection to mssql_database works. But connection to sybase_database ends with this error message:
django.db.utils.DatabaseError: ('42000', "[42000] [FreeTDS][SQL Server]SQL Anywhere Error -265: Procedure 'SERVERPROPERTY' not found (504) (SQLExecDirectW)")
all traceback
$ python manage.py inspectdb --database=sybase_database
Traceback (most recent call last):
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django_pyodbc/base.py", line 491, in execute
return self.cursor.execute(sql, params)
pyodbc.ProgrammingError: ('42000', "[42000] [FreeTDS][SQL Server]SQL Anywhere Error -265: Procedure 'SERVERPROPERTY' not found (504) (SQLExecDirectW)")
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django/core/management/commands/inspectdb.py", line 25, in handle
for line in self.handle_inspection(options):
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django/core/management/commands/inspectdb.py", line 38, in handle_inspection
with connection.cursor() as cursor:
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 162, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django_pyodbc/base.py", line 362, in _cursor
if self.ops.sql_server_ver < 2005:
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django_pyodbc/operations.py", line 138, in _get_sql_server_ver
cur.execute("SELECT CAST(SERVERPROPERTY('ProductVersion') as varchar)")
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
File "/home/pd/packaging/venv/lib/python3.6/site-packages/django_pyodbc/base.py", line 497, in execute
raise utils.DatabaseError(*e.args)
django.db.utils.DatabaseError: ('42000', "[42000] [FreeTDS][SQL Server]SQL Anywhere Error -265: Procedure 'SERVERPROPERTY' not found (504) (SQLExecDirectW)")
$ pip list
Package Version
------------- -------
Django 1.8
django-pyodbc 1.1.3
pip 21.3.1
pyodbc 4.0.32
setuptools 59.6.0
sqlany-django 1.13
sqlanydb 1.0.11
wheel 0.37.1
When I run this script
# hello_sybase.py
import pyodbc
try:
con = pyodbc.connect('Driver={FreeTDS};'
'Server=10.60.1.6,2638;'
'Database=blabla;'
'uid=blabla;pwd=blabla')
cur = con.cursor()
cur.execute("Select * from Test")
for row in cur.fetchall():
print (row)
cur.close()
con.close()
except Exception as e:
print(str(e))
It works and prints all the rows. Is it at least possible to work with the results (rows) in a django template? It's sufficient to have read only database.
According to the site for django-pyodbc, Sybase is not supported.
The traceback leads to this code, which seems to be SQL Server specific. You'd have to hack around to make that library compatible with your database... but since you say you don't necessarily need Django's ORM stuff, you can absolutely just connect to the secondary database using the raw pyodbc layer, e.g.
import pyodbc
# TODO: move this to `settings`?
CONN_STRING = 'Driver={FreeTDS};Server=10.60.1.6,2638;Database=blabla;uid=blabla;pwd=blabla'
def my_view(request):
with pyodbc.connect(CONN_STRING) as conn:
cur = conn.cursor()
cur.execute('SELECT * FROM test')
rows = list(cur.fetchall())
return render(request, 'my_template.html', {'rows': rows})

TypeError: connect() argument 4 must be str, not WindowsPath . /*The Error that i m getting in my simple login django project*/

System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
February 17, 2021 - 19:52:27
Django version 3.1.6, using settings 'felix.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
C:\Users\FELIX\OneDrive\Desktop\Projects\django login2\felix\felix\settings.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner
self.run()
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run
self.check_migrations()
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 459, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__
self.build_graph()
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 216, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations
if self.has_table():
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table
with self.connection.cursor() as cursor:
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor
return self._cursor()
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 235, in _cursor
self.ensure_connection()
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
self.connect()
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection
return Database.connect(**conn_params)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\__init__.py", line 130, in Connect
return Connection(*args, **kwargs)
File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 185, in __init__
super().__init__(*args, **kwargs2)
TypeError: connect() argument 4 must be str, not WindowsPath
I got similar error information while doing makemigrations, and str() worked.
# BASE_DIR = Path(__file__).resolve().parent.parent
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': str(BASE_DIR / 'my.cnf')
}
}
}
TypeError: connect() argument 4 must be str, not WindowsPath, parece referirse a que la línea 4 de la conexión tiene un formato no estándar para el path, solo es revisar el formato de la conexión a DB, por ejemplo:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'project_django_1',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': 3306,
}
}
when you are using mysql you do not needed to give the path just creat database and put the name of database
'ENGINE': 'django.db.backends.mysql',
'NAME': 'your-database-name',
Have you set mysql Database setting?
Please check you set DATABASE right.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbname',
'USER': 'mysql username',
'PASSWORD': 'mysql user password',
'HOST': '127.0.0.1',
'PORT': 3306,
}
}

Django 1.8 create table before reference django_content_type and then fails

I'm trying to create ContentType reference (https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#generic-relations)
myobj/models.py:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
When I start the test (manage.py test -v3), I get traceback:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
super(Command, self).execute(*args, **options)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
failures = test_runner.run_tests(test_labels)
File "/home/alexander/.local/lib/python2.7/site-packages/django/test/runner.py", line 210, in run_tests
old_config = self.setup_databases()
File "/home/alexander/.local/lib/python2.7/site-packages/django/test/runner.py", line 166, in setup_databases
**kwargs
File "/home/alexander/.local/lib/python2.7/site-packages/django/test/runner.py", line 370, in setup_databases
serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
File "/home/alexander/.local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 368, in create_test_db
test_flush=True,
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
return command.execute(*args, **defaults)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle
created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps
cursor.execute(statement)
File "/home/alexander/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/alexander/.local/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/alexander/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: ERROR: reference "django_content_type" does not exist
my settings.py:
...
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'myobj',
)
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'mydb', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': 'pass', # Not used with sqlite3.
'HOST': '127.0.0.1', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '5432', # Set to empty string for default. Not used with sqlite3.
'TEST_NAME': "testdb_%i_%i" % (random.randrange(1,1000000),random.randrange(1,10000000)),
}
}
...
Postgresql log:
ALTER TABLE "myobj_taggeditem" ADD CONSTRAINT "myob_content_type_id_708726b4e928b107_fk_django_content_type_id" FOREIGN KEY ("content_type_id") REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERRED
ERROR: reference "django_content_type" does not exist
If I change DB engine to SQLite everythink is ok.
Whats wrong with it?
I'm using django 1.8
You must create migrations for your myobj app. An unmigrated app cannot depend on a migrated app.
Simply run python manage.py makemigrations myobj and it will create the initial migrations for your app.
The reason it "works" on SQLite3 is that foreign key constraints are not enforced in SQLite by Django.

django.core.exceptions.ImproperlyConfigured: name must be an instance of basestring

I am trying to use Mongodb with in my Django.
Below there are connection settings in settings.py
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': 27017,
}
}
when I am trying to run python manage.py syncdb I am getting an error like this:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_from_command_line(sys.argv)
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/django/core/management/__init__.py", line 429, in execute_from_command_line
utility.execute()
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 59, in handle_noargs
tables = connection.introspection.table_names()
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/django_mongodb_engine-0.4.0-py2.7.egg/django_mongodb_engine/base.py", line 76, in table_names
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/django_mongodb_engine-0.4.0-py2.7.egg/django_mongodb_engine/base.py", line 106, in __getattr__
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/django_mongodb_engine-0.4.0-py2.7.egg/django_mongodb_engine/base.py", line 133, in _connect
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/pymongo-2.4.2-py2.7-linux-x86_64.egg/pymongo/mongo_client.py", line 1025, in __getitem__
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/pymongo-2.4.2-py2.7-linux-x86_64.egg/pymongo/mongo_client.py", line 1014, in __getattr__
File "/home/sakeer/workspace/entevirtual/lib/python2.7/site-packages/pymongo-2.4.2-py2.7-linux-x86_64.egg/pymongo/database.py", line 74, in __init__
django.core.exceptions.ImproperlyConfigured: name must be an instance of basestring
i am using django 1.3
thanks in advance
I've never used mongodb with django, but I'll take a stab just by following the trace. You need to add a value to the NAME setting in your DB configuration
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'foobar',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': 27017,
}
}
The error is being thrown here in pymongo which is created around here via django_mongo_engine

django manage.py raising ImproperlyConfigured error

In attempting to run ./manage.py runserver or shell or any other command for that matter, I'm getting the error: You must define a 'default' database.
I'm running this in a virtualenv and settings.py includes DATABASE_NAME, along with Host, Port and Engine. Where is django expecting definition of the default database?
Here's the traceback:
(env)fox-ser01:common wmfox3$ ./manage.py shell
Traceback (most recent call last):
File "./manage.py", line 31, in <module>
execute_manager(settings)
File "/Users/wmfox3/Sites/photo_project/env/src/django/django/core/management/__init__.py", line 442, in execute_manager
utility.execute()
File "/Users/wmfox3/Sites/photo_project/env/src/django/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/wmfox3/Sites/photo_project/env/src/django/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/wmfox3/Sites/photo_project/env/src/django/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/Users/wmfox3/Sites/photo_project/env/src/django/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/Users/wmfox3/Sites/photo_project/env/src/django/django/core/management/commands/shell.py", line 46, in handle_noargs
from django.db.models.loading import get_models
File "/Users/wmfox3/Sites/photo_project/env/src/django/django/db/__init__.py", line 12, in <module>
raise ImproperlyConfigured("You must define a '%s' database" % DEFAULT_DB_ALIAS)
django.core.exceptions.ImproperlyConfigured: You must define a 'default' database
DATABASE_NAME is deprecated since django 1.2 so if you're using newer version, you should use the new way of defining databases:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
}
define db name is settings.py
DATABASE
Below is an example
DATABASES = {
'default': {
'ENGINE': 'mysql',
'NAME': 'xyz', # db name
'USER': 'root',
'PASSWORD': 'password',
'HOST': '',
'PORT': '',
}
}
In settings.DATABASES.