django-cms / djangocms-transfer

django CMS Transfer allows you to export and import plugins.
https://www.django-cms.org
Other
19 stars 19 forks source link

Import from Python #17

Open arnodeceuninck opened 3 years ago

arnodeceuninck commented 3 years ago

A function which needs the json contents and a page as parameters to import it to a page. This is usefull for seting up standard pages on your site from a custom setup command (e.g. Contact page)

arnodeceuninck commented 3 years ago

This is my current fix for this (only works with exported pages, not plugins):

# Code fragments copy pasted jand modified from djangocms_transfer

import json

from django.core.exceptions import ValidationError
from djangocms_transfer.datastructures import ArchivedPlaceholder
from djangocms_transfer.forms import _object_version_data_hook
from djangocms_transfer.importer import import_plugins_to_page

def import_plugins_from_json(page, json_raw):
    # Warning: Only import pages, not plugins
    data = clean_data(json_raw)
    run_import(data, page)
    return data

def clean_data(json_raw):
    data = _get_parsed_data(json_raw)
    first_item = data[0]
    is_placeholder = isinstance(first_item, ArchivedPlaceholder)
    if not is_placeholder:
        raise ValidationError('Incorrect json format used. You should only export pages, not plugins.')
    return data

def _get_parsed_data(raw):
    return json.loads(raw, object_hook=_object_version_data_hook)

def run_import(cleaned_data, page, language='nl'):
    import_plugins_to_page(
        placeholders=cleaned_data,
        page=page,
        language=language,  # self.current_lang
    )