问题
I can create and publish pages(which I have created by inheriting Page class) by using wagtail admin interface by using the process below.
class HomePage(Page):
template = 'tmp/home.html'
def get_context(self, request):
context = super(HomePage, self).get_context(request)
context['child'] = PatientPage.objects.child_of(self).live()
return context
class PatientPage(Page):
template = 'tmp/patient_page.html'
parent_page_types = ['home.HomePage',]
name = models.CharField(max_length=255, blank=True)
birth_year = models.IntegerField(default=0)
content_panels = Page.content_panels + [
FieldPanel('name'),
FieldPanel('birth_year'),
]
Now, I want to automate creating and publishing of many pages of PatientPage class and append those to Homepage as child by running a python script.
回答1:
This is already answered well here. However, here is a more specific answer to your situation with instructions on how to make this a script that can be run.
To run this custom command script whenever you need, you can create this as a custom django-admin command.
Example: my_app/management/commands/add_pages.py
from django.core.management.base import BaseCommand
from wagtail.wagtailcore.models import Page
from .models import HomePage, PatientPage # assuming your models are in the same app
class Command(BaseCommand):
help = 'Creates many pages'
def handle(self, *args, **options):
# 1 - get your home page
home_page = Page.objects.type(HomePage).first() # this will get the first HomePage
# home_page = Page.objects.get(pk=123) # where 123 is the id of your home page
# just an example - looping through a list of 'titles'
# you could also pass args into your manage.py command and use them here, see the django doc link above.
for page_title in ['a', 'b', 'c']:
# 2 - create a page instance, this is not yet stored in the DB
page = PatientPage(
title=page_title,
slug='new-page-slug-%s'page_title, # pages must be created with a slug, will not auto-create
name='Joe Jenkins', # can leave blank as not required
birth_year=1955,
)
# 3 - create the new page as a child of the parent (home), this puts a new page in the DB
new_page = home_page.add_child(instance=page)
# 4a - create a revision of the page, assuming you want it published now
new_page.save_revision().publish()
# 4b - create a revision of the page, without publishing
new_page.save_revision()
You can run this command using $ python manage.py add_pages
Note: On Python 2, be sure to include __init__.py
files in both the management and management/commands directories as done above or your command will not be detected.
来源:https://stackoverflow.com/questions/47749708/is-there-any-way-to-create-and-publish-pages-by-executing-python-script-in-wagta