Created
October 22, 2021 09:04
-
-
Save truetug/bf9b2523db9aa9dfb3d116fced2296bb to your computer and use it in GitHub Desktop.
That command is for django and wagtail based sites would help if you need to convert all your old blocks to new on every page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import logging | |
import os | |
import uuid | |
from copy import deepcopy | |
from django.conf import settings | |
from django.core.management import BaseCommand | |
from wagtail.core.models import Page | |
logger = logging.getLogger(__name__) | |
class Command(BaseCommand): | |
""" | |
That command is for django and wagtail based sites would help | |
if you need to convert all your old blocks to new on every page | |
(ex if you drop ListBlock for StreamBlock - see https://github.com/wagtail/wagtail-localize/issues/355). | |
Save it to "<app>/management/commands/", review and rewrite handle_block method for your block, | |
dont forget id field, it is important for some actions with content such as wagtail-localize sync translations. | |
""" | |
help = "Convert source block for every page to target using handle_block method" | |
def add_arguments(self, parser): | |
parser.add_argument( | |
"-s", "--source", action="store", dest="source", | |
default="icon_grid", | |
help="ex. icon_grid", | |
) | |
parser.add_argument( | |
"-t", "--target", action="store", dest="target", | |
default="icons", | |
help="ex. icons", | |
) | |
def handle_block(self, block): | |
result = [] | |
for item in block["value"]["items"]: | |
if not item["icon"]: | |
continue | |
result.append({ | |
"id": uuid.uuid4(), | |
"type": "icon", | |
"value": { | |
"caption": item["caption"], | |
"icon": item["icon"], | |
}, | |
}) | |
block["value"]["items"] = result | |
return | |
def handle(self, *args, **options): | |
logger.info("Convert %s to %s", options["source"], options["target"]) | |
qs = Page.objects.all().specific() | |
for page in qs: | |
content = getattr(page, "content", None) | |
if not content: | |
continue | |
content = list(page.content.raw_data) | |
content_new = [] | |
for block in content: | |
if block["type"] == options["target"]: | |
continue | |
elif block["type"] != options["source"]: | |
content_new.append(block) | |
continue | |
block_new = deepcopy(block) | |
self.handle_block(block_new) | |
block_new["type"] = options["target"] | |
# content_new.append(block) | |
content_new.append(block_new) | |
page.content = json.dumps(content_new) | |
page.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment