CustomUser on separate database issues - multiple-databases

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.

Related

OperationalError: no such table: django_content_type and django_session

I cannot access my app, when I enter the URL, it gives me the error
OperationalError: no such table: django_session
This usually means I need to migrate, or delete my sqlite database and redo migrations, so I did that multiple times. I deleted everything in the migrations folder and sqlite3.db and ran:
python manage.py makemigrations app_name
python manage.py migrate app_name
No errors yet. Then after creating a superuser I run:
python manage.py runserver
It tells me 18 migrations have not been made, which I was able to fix with:
python manage.py migrate --fake
I try the site and again I get the no such table: django_session error.
I read this thread
Django: no such table: django_session
and tried everything in it, including the approved solution, same error.
Also, when I try to run the migrate command again, I get this error
OperationalError: no such table: django_content_type
so I went to this thread
sqlite3.OperationalError: no such table: django_content_type
once again, the solutions that worked for them did not work for me.
This problem started after we migrated to MySQL, I tried to switch databases using a .env file, but ran into these problems, so I tried to switch back to sqlite so I can at least work on the project. The team is in the middle of moving to MySQL, and we have people working successfully with both databases, so it shouldn't be a database issue.
Here is my settings.py file:
import os
from pathlib import Path
from django.contrib.messages import constants as message_constants
# 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/
SECRET_KEY = os.environ.get("DJ_SECRET_KEY", default="Testing")
DEBUG = os.environ.get("DJ_DEBUG", default=True)
ALLOWED_HOSTS = ["redonkulator.apps.dev.mach9.usmc.mil", "localhost", "127.0.0.1"]
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"redonkulator_app.apps.RedonkulatorAppConfig",
"jquery",
"debug_toolbar",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.middleware.common.CommonMiddleware",
"debug_toolbar.middleware.DebugToolbarMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
ROOT_URLCONF = "iiimef_project.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["templates"],
"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",
],
},
},
]
AUTH_USER_MODEL = "redonkulator_app.MlptUsers"
WSGI_APPLICATION = "iiimef_project.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
"NAME": os.environ.get(
"SQL_DATABASE",
os.path.join(BASE_DIR, "db.sqlite3"),
),
"USER": os.environ.get("SQL_USER", "user"),
"PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
"HOST": os.environ.get("SQL_HOST", "localhost"),
"PORT": os.environ.get("SQL_PORT", "5432"),
}
}
# 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",
},
]
# 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/"
STATIC_ROOT = os.path.join(BASE_DIR, "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"
LOGIN_REDIRECT_URL = ""
LOGOUT_REDIRECT_URL = "/about"
LOGIN_URL = "/login"
MESSAGE_STORAGE = "django.contrib.messages.storage.cookie.CookieStorage"
# needed to overwrite bootsrap classes
MESSAGE_TAGS = {
message_constants.DEBUG: "debug",
message_constants.INFO: "info",
message_constants.SUCCESS: "success",
message_constants.WARNING: "warning",
message_constants.ERROR: "danger",
}
INTERNAL_IPS = [
"127.0.0.1",
]
I have session and contenttype in my installed apps and sessions in my middleware, is there anything in here that looks obviously wrong?
Here is my .env
DJ_SECRET_KEY=super-secret-key
DJ_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] 0.0.0.0 *
DJ_DEBUG=True
SQL_DATABASE=redonkulator
SQL_ENGINE=django.db.backends.mysql
SQL_USER=[myusername]
SQL_PASSWORD=[mypassword]
SQL_HOST=localhost
SQL_PORT=3306
I know that this .env won't work with my settings, and that's okay as I'm just trying to get sqlite to work for now.
One more thing, starting today, slightly after this problem started, every django import is underlined in yellow. For example "django.contrib.messages" in settings.py is underlined, however I don't get a module import error, so I don't think that's the issue.
Finally, here is the traceback for the content_type error:
Traceback (most recent call last):
File "C:\Users\dwill\Documents\GitHub\MLPT\manage.py", line 22, in <module>
main()
File "C:\Users\dwill\Documents\GitHub\MLPT\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\commands\migrate.py", line 268, in handle
emit_post_migrate_signal(
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\sql.py", line 42, in emit_post_migrate_signal
models.signals.post_migrate.send(
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send
return [
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\management\__init__.py", line 42, in create_permissions
create_contenttypes(app_config, verbosity=verbosity, interactive=interactive, using=using, apps=apps, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\contenttypes\management\__init__.py", line 119, in create_contenttypes
content_types, app_models = get_contenttypes_and_models(app_config, using, ContentType)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\contenttypes\management\__init__.py", line 94, in get_contenttypes_and_models
content_types = {
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 280, in __iter__
self._fetch_all()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_content_type
and the django session error:
Traceback (most recent call last):
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
The above exception (no such table: django_session) was the direct cause of the following exception:
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\admin\sites.py", line 414, in login
return LoginView.as_view(**defaults)(request)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\views.py", line 63, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\views.py", line 92, in form_valid
auth_login(self.request, form.get_user())
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\__init__.py", line 111, in login
request.session.cycle_key()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\base.py", line 344, in cycle_key
self.create()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 51, in create
self._session_key = self._get_new_session_key()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\base.py", line 196, in _get_new_session_key
if not self.exists(session_key):
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 47, in exists
return self.model.objects.filter(session_key=session_key).exists()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 808, in exists
return self.query.has_results(using=self.db)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\query.py", line 550, in has_results
return compiler.has_results()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1145, in has_results
return bool(self.execute_sql(SINGLE))
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 198, in execute
return self._record(self.cursor.execute, sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 133, in _record
return method(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/login/
Exception Value: no such table: django_session
Try avoiding the .env file to rule that out.
Update settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DBNAME',
'USER': 'USER',
'PASSWORD': 'PASS',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
If this works then we have found the source of the problem and should double-check the location of the .env file and work backwards from there.
After making your migrations, try sync your database:
python manage.py migrate --run-syncdb
It has solved this error code for me several times.

Different databases for forms and authentification in django?

Is it possible to use one database for user authentifications in django and another database for working with django-forms? I work with non-relational data structures and feel comfortable with mongodb forms, but I unable to authorize my users, using mongodb. All posts describing mongodb-authentification with django referer to deprecated modules of mongoengine, which is no longer support django. So I decide to use mysql for user authentification and mongodb as main database, but cannot find information about defining special database for user authorization.
UPD:
I add mysql to setings:
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.dummy',
'NAME' : 'my_database'
},
'users': {
'NAME': 'my_users',
'ENGINE': 'django.db.backends.mysql',
'USER': 'django'
}
}
Migrate:
python3 manage.py migrate --database=users
It return:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK
Then I tried to create a user:
set DJANGO_SETTINGS_MODULE=my_site.settings
,
>>> import django
>>> django.setup()
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon#thebeatles.com', 'johnpassword')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 159, in create_user
return self._create_user(username, email, password, **extra_fields)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 153, in _create_user
user.save(using=self._db)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/base_user.py", line 80, in save
super(AbstractBaseUser, self).save(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 807, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 834, in save_base
with transaction.atomic(using=using, savepoint=False):
File "/usr/local/lib/python3.5/dist-packages/django/db/transaction.py", line 158, in __enter__
if not connection.get_autocommit():
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 385, in get_autocommit
self.ensure_connection()
File "/usr/local/lib/python3.5/dist-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.
>>>
Guys, please, advise me, what was the wrong?
UPD2:
Add a router to settings.py:
class AuthRouter(object):
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth_db.
"""
if model._meta.app_label == 'auth':
return 'users'
return 'default'
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth_db.
"""
if model._meta.app_label == 'auth':
return 'users'
return 'default'
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth app is involved.
"""
if obj1._meta.app_label == 'auth' or \
obj2._meta.app_label == 'auth':
return True
return False
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'auth_db'
database.
"""
return db == 'auth_db'
DATABASE_ROUTERS = [AuthRouter]
Now i have enother error, when create user:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 159, in create_user
return self._create_user(username, email, password, **extra_fields)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 153, in _create_user
user.save(using=self._db)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/base_user.py", line 80, in save
super(AbstractBaseUser, self).save(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 766, in save
using = using or router.db_for_write(self.__class__, instance=self)
File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 267, in _route_db
chosen_db = method(model, **hints)
TypeError: db_for_write() missing 1 required positional argument: 'model'
What's wrong in my router? I copied it from oficial docs.

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

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

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