Skip to content

Commit

Permalink
chore: Migration des pages flatpage vers wagtail (#1496)
Browse files Browse the repository at this point in the history
  • Loading branch information
chloend committed Nov 25, 2024
1 parent 43019f7 commit 8c1ce41
Show file tree
Hide file tree
Showing 25 changed files with 229 additions and 765 deletions.
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ shell_on_postgres_container:
populate_db:
pg_restore -d marche --if-exists --clean --no-owner --no-privileges lemarche/perimeters/management/commands/data/perimeters_20220104.sql
ls -d lemarche/fixtures/django/* | xargs django-admin loaddata
djan-admin create_content_pages

populate_db_container:
docker compose exec -ti app bash -c "ls -d lemarche/fixtures/django/* | xargs django-admin loaddata"
docker compose exec -ti app bash -c "django-admin create_content_pages"

# Deployment
# =============================================================================
Expand Down
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,21 @@ django-admin import_departements
django-admin import_communes
```

Des données de test peuvent être chargées ainsi (fixtures) :
### Données de test

- fixtures :
```bash
ls -d lemarche/fixtures/django/* | xargs django-admin loaddata
```

- commande Django :
```bash
django-admin create_content_pages
```

> **Remarque** : La commande `create_content_pages` crée 6 pages de types ContentPage :
('accessibilite', 'cgu', 'cgu-api', 'confidentialite', 'mentions-legales' et 'qui-sommes-nous').

## API

Il y a aussi une API, qui propose plusieurs endpoints et interfaces de documentation :
Expand Down
1 change: 1 addition & 0 deletions clevercloud/review-app-after-success.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ PGPASSWORD=$POSTGRESQL_ADDON_PASSWORD pg_restore -d $POSTGRESQL_ADDON_DB -h $POS
# does not have execution rights on the $APP_HOME directory.
echo "Loading fixtures"
ls -d $APP_HOME/lemarche/fixtures/django/* | xargs django-admin loaddata
django-admin create_content_pages
8 changes: 8 additions & 0 deletions config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,14 @@
# Specific home and purchasing impact page is setted here to avoid queries on every page
SIAE_HOME_PAGE = env.str("SIAE_HOME_PAGE", "/accueil-structure/")
PURCHASING_IMPACT_PAGE = env.str("PURCHASING_IMPACT_PAGE", "/impact-rse/")
# Static pages
ABOUT = env.str("ABOUT", "/qui-sommes-nous/")
ACCESSIBILITY = env.str("ACCESSIBILITY", "/accessibilite/")
CGU = env.str("CGU", "/cgu/")
CGU_API = env.str("CGU_API", "/cgu-api/")
LEGAL_INFO = env.str("LEGAL_INFO", "/mentions-legales/")
PRIVACY_POLICY = env.str("PRIVACY_POLICY", "/confidentialite/")
RESSOURCES = env.str("RESSOURCES", "/ressources/")

# Increase throttling to avoid Bad request errors when saving large pages
# https://docs.djangoproject.com/en/4.2/ref/settings/#data-upload-max-number-fields
Expand Down
55 changes: 55 additions & 0 deletions lemarche/cms/management/commands/create_content_pages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import json

from django.core.management.base import BaseCommand
from wagtail.models import Site

from content_manager.models import ContentPage


class Command(BaseCommand):
help = """
Creates a series of content pages.
"""

def handle(self, *args, **kwargs):
try:
with open("lemarche/fixtures/cms_content_pages.json") as f:
pages_data = json.load(f)
except FileNotFoundError:
self.stdout.write(
self.style.ERROR("Le fichier content_manager/fixtures/cms_content_pages.json n'existe pas.")
)
return
except json.JSONDecodeError:
self.stdout.write(
self.style.ERROR(
"Le fichier content_manager/fixtures/cms_content_pages.json n'est pas un fichier JSON valide."
)
)
return

home_page = Site.objects.filter(is_default_site=True).first().root_page

for page_data in pages_data:
slug = page_data["slug"]
title = page_data["title"]
body = page_data.get("body", [])

self.create_content_page(slug, title, body, home_page)

def create_content_page(self, slug: str, title: str, body: list, parent_page: ContentPage) -> ContentPage:
"""
Creates a page for the site.
"""

# Don't replace or duplicate an already existing page
already_exists = ContentPage.objects.filter(slug=slug).first()
if already_exists:
self.stdout.write(f"The {slug} page seem to already exist with id {already_exists.id}")
return already_exists

new_page = parent_page.add_child(instance=ContentPage(title=title, body=body, slug=slug, show_in_menus=True))

self.stdout.write(self.style.SUCCESS(f"Page {slug} created with id {new_page.id}"))

return new_page
25 changes: 25 additions & 0 deletions lemarche/cms/migrations/0014_homepage_sub_header_custom_message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 4.2.15 on 2024-10-23 10:31

import wagtail.fields
from django.db import migrations


class Migration(migrations.Migration):
dependencies = [
("cms", "0013_alter_articlepage_intro_alter_faqpage_intro"),
]

operations = [
migrations.AddField(
model_name="homepage",
name="sub_header_custom_message",
field=wagtail.fields.StreamField(
[("message", 0)],
blank=True,
block_lookup={0: ("wagtail.blocks.RichTextBlock", (), {"label": "Message personnalisé du bandeau"})},
help_text="Contenu affiché dans le bandeau sous l'en-tête.",
null=True,
verbose_name="Message personnalisé du bandeau",
),
),
]
18 changes: 13 additions & 5 deletions lemarche/cms/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from modelcluster.fields import ParentalManyToManyField
from wagtail import blocks as wagtail_blocks
from wagtail.admin.panels import FieldPanel, MultiFieldPanel
from wagtail.blocks import RichTextBlock
from wagtail.contrib.routable_page.models import RoutablePageMixin, route
from wagtail.fields import RichTextField, StreamField
from wagtail.models import Page
Expand All @@ -14,7 +15,6 @@
from lemarche.cms import blocks
from lemarche.cms.forms import ArticlePageForm
from lemarche.cms.snippets import ArticleCategory
from lemarche.pages.models import PageFragment


class ArticleBase(Page):
Expand Down Expand Up @@ -214,7 +214,18 @@ class HomePage(Page):
use_json_field=True,
)

sub_header_custom_message = StreamField(
[
("message", RichTextBlock(label="Message personnalisé du bandeau")),
],
blank=True,
null=True,
verbose_name="Message personnalisé du bandeau",
help_text="Contenu affiché dans le bandeau sous l'en-tête.",
)

content_panels = Page.content_panels + [
FieldPanel("sub_header_custom_message"),
FieldPanel("banner_title"),
FieldPanel("banner_subtitle"),
FieldPanel("banner_arguments_list"),
Expand All @@ -227,10 +238,7 @@ class HomePage(Page):

def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
try:
context["sub_header_custom_message"] = PageFragment.objects.get(title="Bandeau", is_live=True).content
except PageFragment.DoesNotExist:
pass
context["sub_header_custom_message"] = self.sub_header_custom_message
return context


Expand Down
Empty file added lemarche/cms/tests/__init__.py
Empty file.
43 changes: 43 additions & 0 deletions lemarche/cms/tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import json

from django.core.management import call_command
from django.test import Client, TestCase
from wagtail.models import Site

from content_manager.models import ContentPage


class CreateContentPagesCommandTests(TestCase):
def test_create_content_pages_with_json(self):
client = Client()
with open("lemarche/fixtures/cms_content_pages.json") as f:
pages_data = json.load(f)

call_command("create_content_pages")

# Check that the pages were created
for page_data in pages_data:
slug = page_data["slug"]
self.assertTrue(
ContentPage.objects.filter(slug=slug).exists(), msg=f"La page avec le slug '{slug}' n'a pas été créée."
)

response = client.get(f"/{slug}/")
self.assertEqual(
response.status_code,
200,
msg=f"La page avec le slug '{slug}' n'est pas accessible (status: {response.status_code}).",
)

def test_prevent_duplicate_page_creation(self):
"""Ensure the command does not create duplicate pages"""
home_page = Site.objects.get(is_default_site=True).root_page
home_page.add_child(instance=ContentPage(slug="mentions-legales", title="Mentions légales"))

call_command("create_content_pages")

self.assertEqual(
ContentPage.objects.filter(slug="mentions-legales").count(),
1,
msg="Une page en double a été créée pour le slug 'mentions-legales'.",
)
Loading

0 comments on commit 8c1ce41

Please sign in to comment.