Skip to content

Instantly share code, notes, and snippets.

@stefpiatek
Created November 1, 2017 10:47
Show Gist options
  • Save stefpiatek/1b880e3c7123d917c7cfcec3531285b2 to your computer and use it in GitHub Desktop.
Save stefpiatek/1b880e3c7123d917c7cfcec3531285b2 to your computer and use it in GitHub Desktop.
django auditlog migration error with multiple MySQL databases
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
Django==1.11.6
django-audit-log==0.7.0
mysqlclient==1.3.12
pytz==2017.3
class SecondRouter(object):
"""
A router to control all database operations on models in the
primer app.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read primer_db models go to primer_db.
"""
if model._meta.app_label == 'second':
return 'second'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write primer_db models go to primer_db.
"""
if model._meta.app_label == 'second':
return 'second'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the primer_db app is involved.
"""
if (obj1._meta.app_label == 'second'
or obj2._meta.app_label == 'second'):
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the primer_db app only appears in the 'primer_db'
database.
"""
if db == 'second':
return app_label == 'second'
elif app_label == 'second':
return False
return None
"""
Django settings for project.
Generated by 'django-admin startproject' using Django 1.11.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'o+bv-2mg9h0#kzkmpzbh!e$l*y3#-rrn5w7^fp8+ad$2wf*pz$'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'second'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'audit_log.middleware.UserLoggingMiddleware',
]
ROOT_URLCONF = 'project.urls'
DATABASE_ROUTERS = ['project.database_routers.SecondRouter']
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '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',
],
},
},
]
WSGI_APPLICATION = 'project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'auth',
'USER': 'example',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '3306', },
'second': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'second',
'USER': 'example',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '3306', }
}
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/howto/static-files/
STATIC_URL = '/static/'
"""audit_log URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
"""
WSGI config for audit_log project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "audit_log.settings")
application = get_wsgi_application()
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-01 09:10
from __future__ import unicode_literals
import audit_log.models.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Example',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('is_example', models.BooleanField(default=False)),
],
),
migrations.CreateModel(
name='ExampleAuditLogEntry',
fields=[
('id', models.IntegerField(blank=True, db_index=True)),
('is_example', models.BooleanField(default=False)),
('action_id', models.AutoField(primary_key=True, serialize=False)),
('action_date', models.DateTimeField(default=django.utils.timezone.now, editable=False)),
('action_type', models.CharField(choices=[('I', 'Created'), ('U', 'Changed'), ('D', 'Deleted')], editable=False, max_length=1)),
('action_user', audit_log.models.fields.LastUserField(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='_example_audit_log_entry', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-action_date',),
'default_permissions': (),
},
),
]
from django.db import models
from audit_log.models.managers import AuditLog
class Example(models.Model):
id = models.AutoField(primary_key=True)
is_example = models.BooleanField(default=False)
audit_log = AuditLog()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment