Skip to content

Instantly share code, notes, and snippets.

@wfehr
Last active October 16, 2018 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wfehr/d364589fba8d8d67ef83b133e890ff74 to your computer and use it in GitHub Desktop.
Save wfehr/d364589fba8d8d67ef83b133e890ff74 to your computer and use it in GitHub Desktop.
Helper for migrations in django-cms for plugins which get a model and previously had none.
# anywhere_you_want.py
def create_plugins_from_cmsplugin(new_model_app, new_plugin_model_name,
new_plugin_name, apps=None):
"""
Create plugins for `new_plugin_name` from CMSPlugin-Plugins. This is
necessary if you add a model to a plugin which previously had none.
"""
if apps is None:
from django.apps.registry import apps as dj_apps
apps = dj_apps
try:
cms_plugin = apps.get_model('cms', 'CMSPlugin')
new_model = apps.get_model(new_model_app, new_plugin_model_name)
_new_model = True
except LookupError:
_new_model = False
if _new_model:
old_objects = cms_plugin.objects.filter(plugin_type=new_plugin_name)
for old_obj in old_objects:
new_obj = new_model(
# fields for the cms_cmsplugin table
id=old_obj.id,
position=old_obj.position,
language=old_obj.language,
plugin_type=new_plugin_name,
creation_date=old_obj.creation_date,
changed_date=old_obj.changed_date,
parent=old_obj.parent,
placeholder=old_obj.placeholder,
depth=old_obj.depth,
numchild=old_obj.numchild,
path=old_obj.path,
)
# get all childs
childs = cms_plugin.objects.filter(parent_id=old_obj.id)
# save childs before parent deletion by setting parent_id to NULL
for c in childs:
c.parent_id = None
c.save()
old_obj.delete()
new_obj.save()
# set parent_id again and save childs
for c in childs:
c.parent_id = new_obj.id
c.save()
return _new_model
# my_migration.py
from django.db import migrations
from my_app.where_the_function_lives import create_plugins_from_cmsplugin
def forwards(apps, schema_editor):
_my_model = create_plugins_from_cmsplugin(
'my_app', 'MyCustomPluginModel', 'MyCustomPluginPublisher',
apps)
if not _my_model:
return
class Migration(migrations.Migration):
operations = [
migrations.RunPython(forwards, migrations.RunPython.noop),
]
dependencies = [
('my_app', '00XY_previous_migration_name'),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment