Есть ли способ создать и опубликовать страницы, выполняя сценарий Python в трясогузке?
Я могу создавать и публиковать страницы (которые я создал, унаследовав класс Page), используя интерфейс администратора wagtail, используя процесс, описанный ниже.
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.
1 ответ
Это уже хорошо ответил здесь. Тем не менее, вот более конкретный ответ на вашу ситуацию с инструкциями о том, как сделать этот скрипт, который может быть запущен.
Для запуска этого пользовательского командного сценария, когда вам нужно, вы можете создать его как пользовательскую команду django-admin.
Пример: 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
файлы в каталогах управления и управления / команд, как сделано выше, иначе ваша команда не будет обнаружена.