Django tutorial says I haven't set DATABASE_ENGINE setting yet... but I have - mysql

I'm working through the Django tutorial and receiving the following error when I run the initial python manage.py syncdb:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 362 in execute_manager
utility.execute()
File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 222, in execute
output = self.handle(*args, **options)
File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/Library/Python/2.6/site-packages/django/core/management/commands/syncdb.py", line 49, in handle_noargs
cursor = connection.cursor()
File "/Library/Python/2.6/site-packages/django/db/backends/dummy/base.py", line 15, in complain
raise ImproperlyConfigured, "You haven't set the DATABASE_ENGINE setting yet."
django.core.exceptions.ImproperlyConfigured: You haven't set the DATABASE_ENGINE setting yet.
My settings.py looks like:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dj_tut', # 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.
}
}
I'm guessing this is something simple, but why isn't it seeing the ENGINE setting?

It looks like you are using an earlier version of Django. That way of setting database configuration is from Django 1.2, but the error you are getting is from 1.1. If you are using version 1.1, use this version of the tutorial.

'ENGINE': 'mysql',
'NAME': 'dj_tut',
and you will want to set a user and password.

Same problem happened frequently to me and everytime the problem was cyclic dependencies between sttings.py and another module.

At command prompt you should write:
edit settings.py
then there will be a new module for editing your
settings.py

Related

CustomUser on separate database issues

I want to use the users from a legacy database but keep everything else on the 'default' database.
The main issue I have atm is that I can't get the database router to properly forward queries to the appropriate database. Namely when I run the migrations 2 times, the second time I get an error
~> DJANGO_SETTINGS_MODULE=settings python manage.py makemigrations
Migrations for 'myapp':
myapp/migrations/0001_initial.py
- Create model CustomUser
~> DJANGO_SETTINGS_MODULE=settings python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/manos/workspace/umed/common/oauth2_test/.env/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/manos/workspace/umed/common/oauth2_test/.env/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/manos/workspace/umed/common/oauth2_test/.env/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/manos/workspace/umed/common/oauth2_test/.env/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/manos/workspace/umed/common/oauth2_test/.env/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/manos/workspace/umed/common/oauth2_test/.env/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle
loader.check_consistent_history(connection)
File "/home/manos/workspace/umed/common/oauth2_test/.env/lib/python3.7/site-packages/django/db/migrations/loader.py", line 299, in check_consistent_history
connection.alias,
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency myapp.0001_initial on database 'auth_db'.
So I assume it tries to run the admin stuff inside the auth_db instead of default database. But I can't really figure out what I'm doing wrong since the routing seems correct.
Simplified code below
models.py
class CustomUser(AbstractUser):
password = models.CharField(max_length=128)
username = models.CharField(unique=True, max_length=32)
class Meta:
managed = False
db_table = 'myauthdb_user'
objects = UserManager()
db.py
class AuthRouter:
""" Forwards queries for users models to the auth database. """
def db_for_read(self, model, **hints):
if model.__name__ == 'CustomUser':
return 'auth_db'
return None
settings.py
DATABASE_ROUTERS = ['db.AuthRouter']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': join(BASE_DIR, 'db.app'),
},
'auth_db': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'localhost',
},
}
I can use the ORM just fine e.g. CustomUser.objects.all(). But the migration issue is a huge problem. A naive solution is to disable the admin but I feel the underlying problem is still there.

django manage.py runserver error Unknown system variable 'innodb_strict_mode'"

I'm using python 2.7.14, django 1.11 and mysql 5.7 to my local server and it work fine until i tried to connect in our external mysql 5.1 database and got below error when checking my connection (python manage.py runserver). I suspected because external Mysql is version 5.1. Below is my database setting and error message:
default':
{
'ENGINE': 'django.db.backends.mysql',
#'NAME': os.path.join(BASE_DIR, 'db.mysql'),
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'NAME': 'Mfg',
'USER': 'arastra',
'PASSWORD': '', #no password
'HOST': 'localhost',
'PORT': '3356', # Tunnel set-up.
File "C:\Python27\Lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute
return self.cursor.execute(query, args)
File "C:\Python27\Lib\site-packages\MySQLdb\cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\Lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.OperationalError: (1193, "Unknown system variable 'innodb_strict_mode'")

geodjango with mysql not migrating

I am working on geodjango and just got an issue here geodjango with mysql database resolved. When I ran migrate I got the following error
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 327, in execute
self.check()
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 62, in _run_checks
issues.extend(super(Command, self)._run_checks(**kwargs))
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models
errors.extend(model.check(**kwargs))
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/base.py", line 1283, in check
errors.extend(cls._check_fields(**kwargs))
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/base.py", line 1358, in _check_fields
errors.extend(field.check(**kwargs))
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 219, in check
errors.extend(self._check_backend_specific_checks(**kwargs))
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 322, in _check_backend_specific_checks
return connections[db].validation.check_field(self, **kwargs)
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/backends/mysql/validation.py", line 49, in check_field
field_type = field.db_type(self.connection)
File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.py", line 126, in db_type
return connection.ops.geo_db_type(self)
AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'
This is my database settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'arbithub',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
}
}
further codes would be supplied on request
You need to enable the spatial backend in your DATABASES setting.
For MySQL, replace
'ENGINE': 'django.db.backends.mysql',
with
'ENGINE': 'django.contrib.gis.db.backends.mysql',

Unable to generate migrations in Django 1.11

On a blank MySQL database, I generated migrations for a Django 1.11 project with:
python manage.py makemigrations
I have several custom inter-dependent apps, but all the migrations generated without error. However, when I tried to apply these migrations with:
python manage.py migrate
it applies most app migrations just fine, but with some custom FeinCMS migrations with:
Applying page.0001_initial...Traceback (most recent call last):
File "manage.py", line 9, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 93, in __exit__
self.execute(sql)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute
return self.cursor.execute(query, args)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')
Unfortunately, it doesn't say which foreign key wasn't generated, and the migration has several. I tried commenting out each field in the migration re-running it, but the migration succeeds when I do it that way.
Why is this migration failing and how do I fix it?
You have an issue in Django created tables that table does not have INNODB ENGINE.
In MySql If table has INNODB ENGINE that can make relation as foreign key otherwise Django will return error as mentioned in question
"django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')"
I have solution for this issue.
Firstly create new management command file like name "convert_to_innodb"
and add code as below in that management command file
from django.core.management.base import BaseCommand
from django.db import connections
class Command(BaseCommand):
def handle(self, database="default", *args, **options):
cursor = connections[database].cursor()
cursor.execute("SHOW TABLE STATUS")
for row in cursor.fetchall():
if row[1] != "InnoDB":
print "Converting %s" % row[0],
print cursor.execute("ALTER TABLE %s ENGINE=INNODB" % row[0])
and RUN command in terminal
python manage.py convert_to_innodb
After this command execution you can make foreign key in already created table but
'OPTIONS': {
'init_command': 'SET default_storage_engine=INNODB',
}
add this configuration in DATABASE settings like below
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'USER': 'DB_USER',
'PASSWORD': 'DB_PASSWORD',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
'OPTIONS': {
'init_command': 'SET default_storage_engine=INNODB',
}
}
}
This db configuration will create next time INNODB ENGINE table that will work for future without errors
Because of a bad merge, there were some errors in previous migrations, causing a disconnect between older migrations and the columns in my models. I fixed this by:
deleting all my migrations
truncating my django_migrations table
running manage.py makemigrations
Then migrate worked.

django-balanced - Database Error

I'm trying to install the django-balanced app in my project and I'm getting an error.
I did the following as the readme file says:
#Add to settings
import os
BALANCED = {
'API_KEY': os.environ.get('BALANCED_API_KEY'),
}
INSTALLED_APPS = (
...
'django.contrib.admin', # if you want to use the admin interface
'django_balanced',
...
)
#ran the following on my project root folder
BALANCED_API_KEY=YOUR_API_KEY django-admin.py syncdb #replacing the YOUR_API_KEY with my key
When I do this, I get the following error:
Traceback (most recent call last):
File "/usr/local/bin/django-admin.py", line 5, in <module>
management.execute_from_command_line()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 77, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Library/Python/2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Library/Python/2.7/site-packages/django/core/management/commands/syncdb.py", line 8, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/Library/Python/2.7/site-packages/django/core/management/sql.py", line 9, in <module>
from django.db import models
File "/Library/Python/2.7/site-packages/django/db/__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 46, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
When I do the python manage.py syncdb, I get no errors with the database. I might be missing something in the database setting that the readme file does not mention. Thanks in advance
here is my database settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'payload', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'pass123', # 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.
}
}
You can also type the following command
BALANCED_API_KEY=YOUR_API_KEY python manage.py syncdb
You need to set the DJANGO_SETTINGS_MODULE:
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings