Created
February 29, 2020 04:54
-
-
Save mihow/08765240eeed709af974b15294ce6b39 to your computer and use it in GitHub Desktop.
Add wagtail child page in migrations
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
def add_child_page(parent_page, instance): | |
""" | |
Mimic the behavior of the "add_child" from Django treebeard. | |
We can't use `parent_page.add_child(instance=child_page)` inside of | |
migrations because historical models don't have access to class | |
methods. This replicates the behavior of `add_child` by calculating | |
the treebeard path, path depth and url path. | |
https://django-treebeard.readthedocs.io/en/latest/api.html#treebeard.models.Node.add_child | |
""" | |
child_page = instance | |
child_page_class = child_page.__class__ | |
treebeard_path = '%s00%02d' % (parent_page.path, parent_page.numchild + 1) | |
url_path = '%s%s/' % (parent_page.url_path, child_page.slug) | |
child_page.path = treebeard_path | |
child_page.depth = parent_page.depth + 1 | |
child_page.numchild = 0 | |
child_page.url_path = url_path | |
child_page.save() | |
parent_page.numchild += 1 | |
parent_page.save() | |
return child_page |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment