From 62b59b65ea57c136af82d7e7646726c1a214b3c7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Laur=C3=A9line=20Gu=C3=A9rin?= <zebuline@entrouvert.com>
Date: Thu, 27 Aug 2020 10:05:25 +0200
Subject: [PATCH 1/3] manager: select template when adding a page (#10117)

---
 combo/manager/forms.py | 38 +++++++++++++++++++++-----------
 combo/manager/views.py |  5 +++--
 tests/test_manager.py  | 49 ++++++++++++++++++++++++++++++++++++++++--
 3 files changed, 76 insertions(+), 16 deletions(-)

diff --git a/combo/manager/forms.py b/combo/manager/forms.py
index 02b1944c..bb8c0c26 100644
--- a/combo/manager/forms.py
+++ b/combo/manager/forms.py
@@ -30,6 +30,20 @@ def get_groups_as_choices():
     return [(x.id, x.name) for x in Group.objects.all().order_by('name')]
 
 
+def get_template_name_choices():
+    def template_exists(template):
+        try:
+            get_template(settings.COMBO_PUBLIC_TEMPLATES[template].get('template'))
+        except TemplateDoesNotExist:
+            return False
+        return True
+
+    templates = [(x[0], x[1]['name']) for x in settings.COMBO_PUBLIC_TEMPLATES.items()]
+    templates = [x for x in templates if template_exists(x[0])]
+    templates.sort(key=lambda x: x[1])
+    return templates
+
+
 class PageDuplicateForm(forms.Form):
     title = forms.CharField(label=_('New title'), max_length=150, required=False)
 
@@ -38,6 +52,17 @@ class PageExportForm(forms.Form):
     with_subpages = forms.BooleanField(label=_('Also export subpages'), required=False)
 
 
+class PageAddForm(forms.ModelForm):
+    class Meta:
+        model = Page
+        fields = ('title', 'template_name')
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.fields['template_name'].widget = forms.Select(choices=get_template_name_choices())
+        self.fields['template_name'].initial = settings.COMBO_DEFAULT_PUBLIC_TEMPLATE
+
+
 class PageEditTitleForm(forms.ModelForm):
     class Meta:
         model = Page
@@ -90,18 +115,7 @@ class PageSelectTemplateForm(forms.ModelForm):
 
     def __init__(self, *args, **kwargs):
         super(PageSelectTemplateForm, self).__init__(*args, **kwargs)
-        templates = [(x[0], x[1]['name']) for x in settings.COMBO_PUBLIC_TEMPLATES.items()]
-        templates = [x for x in templates if self.template_exists(x[0])]
-        templates.sort(key=lambda x: x[1])
-        if 'template_name' in self.fields:
-            self.fields['template_name'].widget = forms.Select(choices=templates)
-
-    def template_exists(self, template):
-        try:
-            get_template(settings.COMBO_PUBLIC_TEMPLATES[template].get('template'))
-        except TemplateDoesNotExist:
-            return False
-        return True
+        self.fields['template_name'].widget = forms.Select(choices=get_template_name_choices())
 
 
 class PageEditRedirectionForm(forms.ModelForm):
diff --git a/combo/manager/views.py b/combo/manager/views.py
index 4037e449..25c06774 100644
--- a/combo/manager/views.py
+++ b/combo/manager/views.py
@@ -40,7 +40,7 @@ from combo.data.library import get_cell_class
 from combo.data.utils import export_site, import_site, MissingGroups
 from combo import plugins
 
-from .forms import (PageEditTitleForm, PageVisibilityForm, SiteImportForm,
+from .forms import (PageAddForm, PageEditTitleForm, PageVisibilityForm, SiteImportForm,
         PageEditRedirectionForm, PageSelectTemplateForm, PageEditSlugForm,
         PageEditPictureForm, PageEditIncludeInNavigationForm,
         PageEditDescriptionForm, CellVisibilityForm, PageDuplicateForm, PageExportForm)
@@ -121,7 +121,7 @@ def invalid_cell_report(request):
 class PageAddView(CreateView):
     model = Page
     template_name = 'combo/page_add.html'
-    form_class = PageEditTitleForm
+    form_class = PageAddForm
 
     def get_initial(self):
         initial = super(PageAddView, self).get_initial()
@@ -142,6 +142,7 @@ class PageAddView(CreateView):
     def get_success_url(self):
         return reverse('combo-manager-page-view', kwargs={'pk': self.object.id})
 
+
 page_add = PageAddView.as_view()
 
 
diff --git a/tests/test_manager.py b/tests/test_manager.py
index e9f45c19..7468d2fa 100644
--- a/tests/test_manager.py
+++ b/tests/test_manager.py
@@ -28,6 +28,8 @@ from combo.data.forms import LinkCellForm
 from combo.data.models import (
     Page, CellBase, TextCell, LinkCell, ConfigJsonCell, JsonCell, PageSnapshot,
     LinkListCell, ParentContentCell, MenuCell, ValidityInfo)
+from combo.manager.forms import PageAddForm
+from combo.manager.forms import PageSelectTemplateForm
 from combo.apps.assets.models import Asset
 from combo.apps.family.models import FamilyInfosCell
 from combo.apps.search.models import SearchCell
@@ -79,7 +81,7 @@ def test_add_page(app, admin_user):
     assert resp.location.endswith('/manage/pages/%s/' % page.pk)
     assert page.slug == 'index'
     assert page.title == 'Home'
-    assert page.template_name == 'standard'  # first one was taken
+    assert page.template_name == 'standard'  # default template
     assert page.exclude_from_navigation is True
 
 
@@ -114,6 +116,27 @@ def test_add_child_page(app, admin_user):
     app.get('/manage/pages/42/add/', status=404)
 
 
+def test_page_add_forms(settings):
+    settings.COMBO_PUBLIC_TEMPLATES = {
+        'one': {
+            'name': 'BBB',
+            'template': 'combo/page_template.html',
+        },
+        'two': {
+            'name': 'AAA',
+            'template': 'combo/page_template_sidebar.html',
+        },
+        'unknown': {
+            'name': 'Unknown',
+            'template': 'combo/unknown.html',
+        },
+    }
+    settings.COMBO_DEFAULT_PUBLIC_TEMPLATE = 'one'
+    form = PageAddForm()
+    assert form.fields['template_name'].widget.choices == [('two', 'AAA'), ('one', 'BBB')]
+    assert form['template_name'].initial == 'one'
+
+
 def test_edit_page(app, admin_user):
     Page.objects.all().delete()
     app = login(app)
@@ -142,7 +165,7 @@ def test_edit_page(app, admin_user):
     # template name
     resp = resp.click(href='.*/template')
     assert resp.form['template_name'].value == 'standard'
-    assert len(resp.form['template_name'].options) == 2 # by default there are 2 templates
+    assert len(resp.form['template_name'].options) == 2  # by default there are 2 templates
     resp.form['template_name'].value = 'standard-sidebar'
     resp = resp.form.submit()
     resp = resp.follow()
@@ -169,6 +192,28 @@ def test_edit_page(app, admin_user):
     assert Page.objects.all()[0].exclude_from_navigation is False
 
 
+def test_page_edit_template_form(settings):
+    page = Page.objects.create(title='One', slug='one', template_name='two')
+    settings.COMBO_PUBLIC_TEMPLATES = {
+        'one': {
+            'name': 'BBB',
+            'template': 'combo/page_template.html',
+        },
+        'two': {
+            'name': 'AAA',
+            'template': 'combo/page_template_sidebar.html',
+        },
+        'unknown': {
+            'name': 'Unknown',
+            'template': 'combo/unknown.html',
+        },
+    }
+    settings.COMBO_DEFAULT_PUBLIC_TEMPLATE = 'one'
+    form = PageSelectTemplateForm(instance=page)
+    assert form.fields['template_name'].widget.choices == [('two', 'AAA'), ('one', 'BBB')]
+    assert form['template_name'].initial == 'two'
+
+
 def test_edit_page_cell_invalid_placeholder(freezer, app, admin_user):
     freezer.move_to('2020-06-05 12:00:01')
     page = Page.objects.create(title='One', slug='one', template_name='standard')
-- 
2.28.0

