WagtailWagtail

How to add Wagtail page programmatically via Python script

Feb 27, 2018 · Updated: Jul 12, 2021 · by Tim Kamanin

Given:

Two Wagtail CMS page classes:

class Section(Page):
    subtitle = models.Charfield(max_length=128)


class News(Page):
    content = models.Textfield()

Task:

Using a python script, add a News page item under the Section page titled "Latest news."

Solution:

  1. Get parent page instance:

    parent_page = Page.objects.get(title="Latest news").specific
    

  2. Create a News page instance:

    news_page = News(content="Something pleasant to hear.")
    

  3. Add newly created instance as a child to the parent_page:

    parent_page.add_child(instance=news_page)
    

  4. Save news_page:

    news_page.save()
    

Now you should see your page in the Wagtail explorer. Done!

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓