我可以使用wagtail管理界面通过以下过程创建和发布页面(我通过继承Page类创建的页面)。
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'),
]
现在,我希望自动创建和发布PatientPage类的许多页面,并通过运行python脚本将这些页面作为子项附加到主页。
答案 0 :(得分:2)
这已经得到了很好的解答here。但是,这里有一个更具体的答案,说明如何使这个脚本可以运行。
要在需要时运行此自定义命令脚本,您可以将其创建为custom django-admin command。
示例: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()
您可以使用$ python manage.py add_pages
注意:在Python 2上,请确保在管理和管理/命令目录中包含__init__.py
文件,如上所述,否则将无法检测到您的命令。