Skip to content

Commit

Permalink
Add a script that creates 3 pages
Browse files Browse the repository at this point in the history
  • Loading branch information
Ash-Crow committed Nov 30, 2023
1 parent e8a5552 commit d9e5351
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 24 deletions.
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ init:
$(EXEC_CMD) poetry run pre-commit install
$(EXEC_CMD) poetry run python manage.py migrate
$(EXEC_CMD) poetry run python manage.py collectstatic --noinput
$(EXEC_CMD) poetry run python manage.py create_sample_pages

.PHONY: runserver
runserver:
Expand Down
137 changes: 113 additions & 24 deletions content_manager/management/commands/create_sample_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,62 +2,123 @@
from django.urls import reverse
from wagtail.models import Page, Site
from wagtail.rich_text import RichText
from wagtailmenus.models.menuitems import FlatMenuItem

from content_manager.models import ContentPage
from content_manager.utils import get_or_create_footer_menu, import_image


ALL_ALLOWED_SLUGS = ["home", "mentions-legales", "accessibilite"]


class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("--slug", nargs="+", type=str, help="[Optional] Slug of the page(s) to create")
parser.add_argument(
"--slug", nargs="+", type=str, help="[Optional] Slug of the page(s) to create", choices=ALL_ALLOWED_SLUGS
)

def handle(self, *args, **kwargs):
slugs = kwargs.get("slug")

if not slugs:
slugs = ["home"]
slugs = ALL_ALLOWED_SLUGS

for slug in slugs:
self.create_page(slug)

def create_page(self, slug: str):
if slug == "home":
self.create_page_home()
else:
raise ValueError(f"Valeur inconnue : {slug}")

def create_page_home(self):
if slug == "home":
self.create_homepage()
elif slug == "mentions-legales":
title = "Mentions légales"
body = []
alert_block = {
"title": title,
"description": """Entrez ici les mentions légales du site.<br />
<a href="https://www.francenum.gouv.fr/guides-et-conseils/developpement-commercial/site-web/quelles-sont-les-mentions-legales-pour-un-site">
Que doivent-elles obligatoirement contenir ?</a>""", # noqa
"level": "info",
}
body.append(("alert", alert_block))

text_raw = """
<p>D’après la <a href="https://www.systeme-de-design.gouv.fr/elements-d-interface/composants/pied-de-page">documentation du système de design</a>,
le pied de page doit contenir a minima les quatre liens suivants :</p>
<ul>
<li>Accessibilité : non/partiellement/totalement conforme</li>
<li>Mentions légales</li>
<li>Données personnelles</li>
<li>Gestion des cookies</li>
</ul>
<p>Ces deux derniers peuvent pointer vers des pages à part entière ou des sections de cette page.</p>
""" # noqa
body.append(("paragraphlarge", RichText(text_raw)))

self.create_page(slug=slug, title=title, body=body)
elif slug == "accessibilite":
title = "Déclaration d’accessibilité"
body = []
alert_block = {
"title": title,
"description": """Entrez ici la déclaration d’accessibilité.<br />
<a href="https://betagouv.github.io/a11y-generateur-declaration/#create">
Générateur de déclaration d’accessibilité</a>""",
"level": "info",
}

body.append(("alert", alert_block))
self.create_page(slug=slug, title=title, body=body, footer_label="Accessibilité : non conforme")
else:
raise ValueError(f"Valeur inconnue : {slug}")

def create_homepage(self) -> None:
"""
Create the home page, set it as default and delete the sample page
Create the homepage, set it as default and delete the sample page
"""
# Don't replace a manually created home
already_exists = ContentPage.objects.filter(slug="home").first()
if already_exists:
raise ValueError(f"The home page seem to already exist with id {already_exists.id}")

# Create the page
title = "Votre nouveau site avec le CMS beta"
body = []

body.append(("title", {"title": title, "large": True}))
body.append(("title", {"title": "Votre nouveau site avec le CMS Beta", "large": True}))

image = import_image(
full_path="staticfiles/dsfr/dist/artwork/pictograms/digital/coding.svg",
title="Pictogrammes DSFR — Internet",
)

body_raw = f"""<p>Bienvenue !</p>
text_raw = """<p>Bienvenue !</p>
<p>Vous venez de créer un site utilisant le gestionnaire de contenus de l’État.</p>
<p>Vous pouvez maintenant <a href="{ reverse('wagtailadmin_home')}">vous connecter dans l’administration</a>
et personnaliser le site.</p>
<p>Vous pouvez maintenant vous connecter dans l’administration et personnaliser le site.</p>
"""

image_and_text_block = {
"image": image,
"image_ratio": "3",
"text": RichText(text_raw),
"link_url": reverse("wagtailadmin_home"),
"link_label": "Gérer le site",
}

body.append(("imageandtext", image_and_text_block))

<p>En particulier, n'hésitez pas à :
text_2_raw = """
<p>En particulier, vous devrez :</p>
<ul>
<li>Remplacer les paramètres par défaut du site dans Configuration > Configuration du site</li>
<li>Configurer le site dans Configuration > Configuration du site</li>
<li>Remplacer le contenu de la page de mentions légales</li>
<li>Remplacer le contenu de cette page d’accueil.</li>
</ul>
"""

body.append(("paragraph", RichText(body_raw)))
body.append(("paragraphlarge", RichText(text_2_raw)))

root = Page.objects.get(slug="root")
home_page = root.add_child(instance=ContentPage(title=title, body=body))
home_page = root.add_child(instance=ContentPage(title="Accueil", body=body, show_in_menus=True))

# Define it as default
site = Site.objects.first()
# Define it as default for the default site
site = Site.objects.filter(is_default_site=True).first()

site.root_page_id = home_page.id
site.save()
Expand All @@ -68,3 +129,31 @@ def create_page_home(self):

home_page.slug = "home"
home_page.save()

self.stdout.write(self.style.SUCCESS(f"Homepage created with id {home_page.id}"))

def create_page(self, slug: str, title: str, body: list, footer_label: str = ""):
"""
Creates a page for the site and adds it to the footer
"""

# Don't replace a manually created page
already_exists = ContentPage.objects.filter(slug=slug).first()
if already_exists:
raise ValueError(f"The {slug} page seem to already exist with id {already_exists.id}")

home_page = Page.objects.get(slug="home")
new_page = home_page.add_child(instance=ContentPage(title=title, body=body, slug=slug, show_in_menus=True))

footer_menu = get_or_create_footer_menu()

footer_item = {
"menu": footer_menu,
"link_page": new_page,
}
if footer_label:
footer_item["link_text"] = footer_label

FlatMenuItem.objects.create(**footer_item)

self.stdout.write(self.style.SUCCESS(f"Page {slug} created with id {new_page.id}"))
35 changes: 35 additions & 0 deletions content_manager/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from io import BytesIO

from django.core.files.images import ImageFile
from wagtail.images.models import Image
from wagtail.models import Site
from wagtailmenus.models.menus import FlatMenu


def import_image(full_path: str, title: str) -> Image:
"""
Import an image to the Wagtail medias based on its full path and return it.
"""
with open(full_path, "rb") as image_file:
image = Image(
file=ImageFile(BytesIO(image_file.read()), name=title),
title=title,
)
image.save()
return image


def get_or_create_footer_menu() -> FlatMenu:
"""
Get the footer menu or create it if it doesn't already exist
In any case, return it.
"""

footer_menu = FlatMenu.objects.filter(handle="footer").first()

if not footer_menu:
default_site = Site.objects.filter(is_default_site=True).first()
footer_menu = FlatMenu.objects.create(title="Pied de page", handle="footer", site=default_site)

return footer_menu

0 comments on commit d9e5351

Please sign in to comment.