forked from django-cms/django-cms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
forms.py
1513 lines (1262 loc) · 50.8 KB
/
forms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from django import forms
from django.apps import apps
from django.contrib.auth import get_permission_codename, get_user_model
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.forms.utils import ErrorList
from django.forms.widgets import HiddenInput
from django.utils import timezone
from django.utils.encoding import force_str
from django.utils.functional import cached_property
from django.utils.translation import get_language, gettext, gettext_lazy as _
from cms import api
from cms.apphook_pool import apphook_pool
from cms.cache.permissions import clear_permission_cache
from cms.constants import PAGE_TYPES_ID, ROOT_USER_LEVEL
from cms.exceptions import PluginLimitReached
from cms.extensions import extension_pool
from cms.forms.fields import PageSmartLinkField
from cms.forms.validators import validate_relative_url, validate_url_uniqueness
from cms.forms.widgets import (
AppHookSelect,
ApplicationConfigSelect,
UserSelectAdminWidget,
)
from cms.models import (
CMSPlugin,
GlobalPagePermission,
Page,
PageContent,
PagePermission,
PageType,
PageUser,
PageUserGroup,
Placeholder,
TreeNode,
)
from cms.models.permissionmodels import User
from cms.operations import ADD_PAGE_TRANSLATION, CHANGE_PAGE_TRANSLATION
from cms.operations.helpers import (
send_post_page_operation,
send_pre_page_operation,
)
from cms.plugin_pool import plugin_pool
from cms.signals.apphook import set_restart_trigger
from cms.utils.compat.forms import UserChangeForm
from cms.utils.conf import get_cms_setting, get_subordinate_groups, get_subordinate_users
from cms.utils.i18n import get_language_list, get_site_language_from_request
from cms.utils.page import get_clean_username
from cms.utils.permissions import get_current_user, get_user_permission_level
from cms.utils.urlutils import static_with_version
from menus.menu_pool import menu_pool
def get_permission_accessor(obj):
User = get_user_model()
if isinstance(
obj,
(
PageUser,
User,
),
):
rel_name = "user_permissions"
else:
rel_name = "permissions"
return getattr(obj, rel_name)
def get_page_changed_by_filter_choices():
# This is not site-aware
# Been like this forever
# Would be nice for it to filter out by site
values = (
Page.objects.distinct()
.order_by("changed_by")
.values_list("changed_by", flat=True)
)
yield ("", _("All"))
for value in values:
yield (value, value)
def get_page_template_filter_choices():
yield ("", _("All"))
for value, name in get_cms_setting("TEMPLATES"):
yield (value, name)
def save_permissions(data, obj):
models = (
(Page, "page"),
(PageUser, "pageuser"),
(PageUserGroup, "pageuser"),
(PagePermission, "pagepermission"),
)
if not obj.pk:
# save obj, otherwise we can't assign permissions to him
obj.save()
permission_accessor = get_permission_accessor(obj)
for model, name in models:
content_type = ContentType.objects.get_for_model(model)
for key in ("add", "change", "delete"):
# add permission `key` for model `model`
codename = get_permission_codename(key, model._meta)
permission = Permission.objects.get(
content_type=content_type, codename=codename
)
field = "can_%s_%s" % (key, name)
if data.get(field):
permission_accessor.add(permission)
elif field in data:
permission_accessor.remove(permission)
class CopyPermissionForm(forms.Form):
"""
Holds the specific field for permissions
"""
copy_permissions = forms.BooleanField(
label=_("Copy permissions"),
required=False,
initial=True,
)
class SlugWidget(forms.widgets.TextInput):
"""
Special widget for the slug field that requires Title field to be there.
Adds the js for the slugifying.
"""
def __init__(self, attrs=None):
if attrs is None:
attrs = {}
else:
attrs = attrs.copy()
language = attrs.get("language", get_language())
self.uhd_lang, self.uhd_urls = self.get_unihandecode_settings(language)
attrs["data-decoder"] = self.uhd_lang
super().__init__(attrs)
def get_unihandecode_settings(self, language):
if language[:2] in get_cms_setting("UNIHANDECODE_DECODERS"):
uhd_lang = language[:2]
else:
uhd_lang = get_cms_setting("UNIHANDECODE_DEFAULT_DECODER")
uhd_host = get_cms_setting("UNIHANDECODE_HOST")
uhd_version = get_cms_setting("UNIHANDECODE_VERSION")
if uhd_lang and uhd_host and uhd_version:
uhd_urls = [
f"{uhd_host}unihandecode-{uhd_version}.core.min.js",
f"{uhd_host}unihandecode-{uhd_version}.{uhd_lang}.min.js",
]
else:
uhd_urls = []
return uhd_lang, uhd_urls
@property
def media(self):
js_media = [
"admin/js/urlify.js",
static_with_version("cms/js/dist/bundle.forms.slugwidget.min.js"),
] + self.uhd_urls
return forms.Media(js=js_media)
class BasePageContentForm(forms.ModelForm):
_site = None
_request = None
title = forms.CharField(
label=_("Title"),
max_length=255,
widget=forms.TextInput(),
help_text=_("The default title"),
)
slug = forms.SlugField(
label=_("Slug"),
max_length=255,
help_text=_("The part of the title that is used in the URL"),
)
menu_title = forms.CharField(
label=_("Menu Title"),
widget=forms.TextInput(),
help_text=_("Overwrite what is displayed in the menu"),
required=False,
)
page_title = forms.CharField(
label=_("Page Title"),
widget=forms.TextInput(),
required=False,
help_text=_(
"Overwrites what is displayed at the top of your browser or in bookmarks"
),
)
meta_description = forms.CharField(
label=_("Description meta tag"),
max_length=320,
required=False,
widget=forms.Textarea(attrs={"maxlength": "320", "rows": "4"}),
help_text=_("A description of the page used by search engines."),
)
class Meta:
model = PageContent
fields = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
attrs = dict(self.fields["slug"].widget.attrs or {}, language=self._language)
self.fields["slug"].widget = SlugWidget(attrs=attrs)
@cached_property
def _language(self):
return get_site_language_from_request(self._request, site_id=self._site.pk)
@property
def _user(self):
return self._request.user
class AddPageForm(BasePageContentForm):
source = forms.ModelChoiceField(
label=_("Page type"),
queryset=Page.objects.filter(is_page_type=True),
required=False,
)
cms_page = forms.ModelChoiceField(
queryset=Page.objects.all(),
required=False,
widget=forms.HiddenInput(),
)
parent_node = forms.ModelChoiceField(
queryset=TreeNode.objects.all(),
required=False,
widget=forms.HiddenInput(),
)
edit = forms.IntegerField(
# Got to edit/preview mode after adding
required=False,
widget=forms.HiddenInput(),
)
content_defaults = {
'in_navigation': get_cms_setting('DEFAULT_IN_NAVIGATION'),
}
class Meta:
model = PageContent
fields = ["source"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
source_field = self.fields.get("source")
if not source_field or source_field.widget.is_hidden:
return
page_field = self.fields.get("cms_page")
if page_field:
page_field.queryset = page_field.queryset.filter(node__site=self._site)
root_page = PageType.get_root_page(site=self._site)
if root_page:
# Set the choicefield's choices to the various page_types
descendants = root_page.get_descendant_pages().filter(is_page_type=True)
titles = PageContent.objects.filter(
page__in=descendants, language=self._language
)
choices = [("", "---------")]
choices.extend((title.page_id, title.title) for title in titles)
source_field.choices = choices
else:
choices = []
if len(choices) < 2:
source_field.widget = forms.HiddenInput()
def clean_slug(self):
slug = self.cleaned_data['slug']
if slug != slug.lower():
raise ValidationError("Slug must have all characters in lowercase")
return slug
def clean(self):
data = self.cleaned_data
if self._errors:
# Form already has errors, best to let those be
# addressed first.
return data
parent_node = data.get("parent_node")
if parent_node:
slug = data["slug"]
parent_path = parent_node.item.get_path(self._language)
path = "%s/%s" % (parent_path, slug) if parent_path else slug
else:
path = data["slug"]
try:
# Validate the url
validate_url_uniqueness(
self._site,
path=path,
language=self._language,
user_language=self._language,
)
except ValidationError as error:
self.add_error("slug", error)
else:
data["path"] = path
return data
def clean_parent_node(self):
parent_node = self.cleaned_data.get("parent_node")
if parent_node and parent_node.site_id != self._site.pk:
raise ValidationError("Site doesn't match the parent's page site")
return parent_node
def create_translation(self, page):
data = self.cleaned_data
title_kwargs = {
"page": page,
"language": self._language,
"slug": data["slug"],
"path": data["path"],
"title": data["title"],
"template": self.get_template(),
"created_by": self._user,
}
title_kwargs.update(self.content_defaults)
if "menu_title" in data:
title_kwargs["menu_title"] = data["menu_title"]
if "page_title" in data:
title_kwargs["page_title"] = data["page_title"]
if "meta_description" in data:
title_kwargs["meta_description"] = data["meta_description"]
return api.create_page_content(**title_kwargs)
def from_source(self, source, parent=None):
new_page = source.copy(
site=self._site,
parent_node=parent,
language=self._language,
translations=False,
permissions=False,
extensions=False,
user=self._user,
)
new_page.update(is_page_type=False)
return new_page
def get_template(self):
source = self.cleaned_data.get("source")
if source:
return source.get_template(self._language)
return PageContent.TEMPLATE_DEFAULT
def save(self, *args, **kwargs):
page = self.cleaned_data.get("cms_page")
source = self.cleaned_data.get("source")
parent = self.cleaned_data.get("parent_node")
operation_token = send_pre_page_operation(
request=self._request,
operation=ADD_PAGE_TRANSLATION,
language=self._language,
)
if page:
new_page = page
elif source:
new_page = self.from_source(source, parent=parent)
else:
new_page = Page()
new_page.set_tree_node(self._site, target=parent, position="last-child")
new_page.save()
translation = self.create_translation(new_page)
new_page.page_content_cache[translation.language] = translation
if source:
extension_pool.copy_extensions(
source_page=source,
target_page=new_page,
languages=[translation.language],
)
placeholders = source.get_placeholders(translation.language)
for source_placeholder in placeholders:
target_placeholder = translation.placeholders.create(
slot=source_placeholder.slot,
default_width=source_placeholder.default_width,
)
source_placeholder.copy_plugins(
target_placeholder, language=translation.language
)
is_first = not (
TreeNode.objects.get_for_site(self._site)
.exclude(pk=new_page.node_id)
.exists()
)
if is_first and not new_page.is_page_type:
# its the first page. Make it the homepage
new_page.set_as_homepage(self._user)
send_post_page_operation(
request=self._request,
operation=ADD_PAGE_TRANSLATION,
token=operation_token,
obj=new_page,
language=self._language,
)
return translation
def save_m2m(self):
return
class AddPageTypeForm(AddPageForm):
menu_title = None
meta_description = None
page_title = None
source = forms.ModelChoiceField(
queryset=Page.objects.all(),
required=False,
widget=forms.HiddenInput(),
)
content_defaults = {
"in_navigation": False,
}
def get_or_create_root(self):
"""
Creates the root node used to store all page types
for the current site if it doesn't exist.
"""
root_page = PageType.get_root_page(site=self._site)
if not root_page:
root_page = Page(is_page_type=True)
root_page.set_tree_node(self._site)
root_page.save()
if not root_page.has_translation(self._language):
api.create_page_content(
language=self._language,
title=gettext("Page Types"),
page=root_page,
slug=PAGE_TYPES_ID,
path=PAGE_TYPES_ID,
in_navigation=False,
)
return root_page.node
def clean_parent_node(self):
parent_node = super().clean_parent_node()
if parent_node and not parent_node.item.is_page_type:
raise ValidationError("Parent has to be a page type.")
if not parent_node:
# parent was not explicitly selected.
# fallback to the page types root
parent_node = self.get_or_create_root()
return parent_node
def from_source(self, source, parent=None):
new_page = source.copy(
site=self._site,
parent_node=parent,
language=self._language,
translations=False,
permissions=False,
extensions=False,
)
new_page.update(is_page_type=True)
return new_page
def save(self, *args, **kwargs):
new_page = super().save(*args, **kwargs)
if not self.cleaned_data.get("source"):
# User has created a page-type via "Add page"
# instead of from another page.
new_page.update(is_page_type=True)
return new_page
class DuplicatePageForm(AddPageForm):
source = forms.ModelChoiceField(
queryset=Page.objects.all(),
required=True,
widget=forms.HiddenInput(),
)
class ChangePageForm(BasePageContentForm):
overwrite_url = forms.CharField(
label=_("Overwrite URL"),
max_length=255,
required=False,
help_text=_("Keep this field empty if standard path should be used."),
)
soft_root = forms.BooleanField(
label=_("Soft root"),
required=False,
help_text=_("All ancestors will not be displayed in the navigation"),
)
redirect = PageSmartLinkField(
label=_("Redirect"),
required=False,
help_text=_("Redirects to this URL."),
placeholder_text=_("Start typing..."),
ajax_view="admin:cms_page_get_list",
)
limit_visibility_in_menu = forms.TypedChoiceField(
choices=PageContent._meta.get_field("limit_visibility_in_menu").choices,
label=_("menu visibility"),
help_text=_("limit when this page is visible in the menu"),
initial=PageContent._meta.get_field("limit_visibility_in_menu").default,
required=False,
coerce=int,
empty_value=None,
)
fieldsets = (
(
None,
{
"fields": (
"title",
"slug",
"template",
"page_title",
"meta_description",
),
},
),
(
_("URL options"),
{
"fields": ("overwrite_url", "redirect"),
"classes": ["collapse"],
},
),
(
_("Menu options"),
{
"fields": ("soft_root", "menu_title", "limit_visibility_in_menu"),
"classes": ["collapse"],
},
),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.url_obj = self.instance.page.get_url(self._language)
self.fields["slug"].initial = self.url_obj.slug
self.fields["redirect"].widget.language = self._language
self.fields["redirect"].initial = self.instance.redirect
if not self.url_obj.managed:
self.fields["overwrite_url"].initial = self.url_obj.path
@cached_property
def _language(self):
return self.instance.language
def clean(self):
data = super().clean()
if self._errors:
# Form already has errors, best to let those be
# addressed first.
return data
page = self.instance.page
if page.is_home:
data["path"] = ""
return data
slug = data["slug"]
path_override = self.cleaned_data.get("overwrite_url")
parent_page = page.parent_page
if path_override:
path = path_override.strip("/")
elif parent_page and parent_page.is_home:
path = slug
elif parent_page:
base_path = parent_page.get_path(self._language)
path = "%s/%s" % (base_path, slug) if base_path else None
else:
path = slug
if path is None:
data["path"] = None
return data
user_language = get_site_language_from_request(
self._request, site_id=self._site.pk
)
try:
# Validate the url
validate_url_uniqueness(
self._site,
path=path,
language=self._language,
user_language=user_language,
exclude_page=page,
)
except ValidationError as error:
field = "overwrite_url" if path_override else "slug"
self.add_error(field, error)
else:
data["path"] = path
return data
def clean_xframe_options(self):
if "xframe_options" not in self.fields:
return # nothing to do, field isn't present
xframe_options = self.cleaned_data["xframe_options"]
if xframe_options == "":
return PageContent._meta.get_field("xframe_options").default
return xframe_options
def save(self, commit=True):
operation_token = send_pre_page_operation(
request=self._request,
operation=CHANGE_PAGE_TRANSLATION,
language=self._language,
)
data = self.cleaned_data.copy()
page = self.instance.page
page_slug = data.pop("slug", None)
page_path = data.pop("path", None)
page_overwrite_url = data.pop("overwrite_url", None)
page_content = super().save(commit=False)
page_content.update(
changed_by=get_clean_username(self._request.user),
changed_date=timezone.now(),
**data,
)
page.update_urls(
self._language,
path=page_path,
slug=page_slug,
managed=not bool(page_overwrite_url),
)
page._update_url_path_recursive(self._language)
page.clear_cache(menu=True)
if page.application_urls and "slug" in self.changed_data:
# Connects the apphook restart handler to the request finished signal
set_restart_trigger()
send_post_page_operation(
request=self._request,
operation=CHANGE_PAGE_TRANSLATION,
token=operation_token,
obj=page,
language=self._language,
)
return page_content
class AdvancedSettingsForm(forms.ModelForm):
_site = None
_request = None
application_urls = forms.ChoiceField(
label=_("Application"),
choices=(),
required=False,
help_text=_("Hook application to this page."),
)
# This is really a 'fake' field which does not correspond to any Page attribute
# But creates a stub field to be populate by js
application_configs = forms.CharField(
label=_("Application configurations"),
required=False,
widget=ApplicationConfigSelect,
)
class Meta:
model = Page
fields = [
"login_required",
"reverse_id",
"navigation_extenders",
"application_urls",
"application_namespace",
"application_configs",
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if "navigation_extenders" in self.fields:
navigation_extenders = self.get_navigation_extenders()
self.fields["navigation_extenders"].widget = forms.Select(
{}, [("", "---------")] + navigation_extenders
)
if "application_urls" in self.fields:
# Prepare a dict mapping the apps by class name ('PollApp') to
# their app_name attribute ('polls'), if any.
app_namespaces = {}
app_configs = {}
for hook in apphook_pool.get_apphooks():
app = apphook_pool.get_apphook(hook[0])
if app.app_name:
app_namespaces[hook[0]] = app.app_name
if app.app_config:
app_configs[hook[0]] = app
self.fields["application_urls"].widget = AppHookSelect(
attrs={"id": "application_urls"}, app_namespaces=app_namespaces
)
self.fields["application_urls"].choices = [
("", "---------")
] + apphook_pool.get_apphooks()
page_data = self.data if self.data else self.initial
if app_configs:
self.fields["application_configs"].widget = ApplicationConfigSelect(
attrs={"id": "application_configs"},
app_configs=app_configs,
)
if (
page_data.get("application_urls", False)
and page_data["application_urls"] in app_configs
):
configs = app_configs[page_data["application_urls"]].get_configs()
self.fields["application_configs"].widget.choices = [
(config.pk, force_str(config)) for config in configs
]
try:
config = configs.get(
namespace=self.initial["application_namespace"]
)
self.fields["application_configs"].initial = config.pk
except ObjectDoesNotExist:
# Provided apphook configuration doesn't exist (anymore),
# just skip it
# The user will choose another value anyway
pass
@cached_property
def _language(self):
return get_site_language_from_request(self._request, site_id=self._site.pk)
def clean(self):
cleaned_data = super().clean()
if self._errors:
# Fail fast if there's errors in the form
return cleaned_data
if "reverse_id" in self.fields:
reverse_id = cleaned_data["reverse_id"]
if reverse_id:
lookup = Page.objects.on_site(self._site).filter(reverse_id=reverse_id)
if lookup.exclude(pk=self.instance.pk).exists():
self._errors["reverse_id"] = self.error_class(
[_("A page with this reverse URL id exists already.")]
)
apphook = cleaned_data.get("application_urls", None)
# The field 'application_namespace' is a misnomer. It should be
# 'instance_namespace'.
instance_namespace = cleaned_data.get("application_namespace", None)
application_config = cleaned_data.get("application_configs", None)
if apphook:
apphooks_with_config = self.get_apphooks_with_config()
# application_config wins over application_namespace
if apphook in apphooks_with_config and application_config:
# the value of the application config namespace is saved in
# the 'usual' namespace field to be backward compatible
# with existing apphooks
try:
appconfig_pk = forms.IntegerField(required=True).to_python(
application_config
)
except ValidationError:
self._errors["application_configs"] = ErrorList(
[_("Invalid application config value")]
)
return self.cleaned_data
try:
config = (
apphooks_with_config[apphook].get_configs().get(pk=appconfig_pk)
)
except ObjectDoesNotExist:
self._errors["application_configs"] = ErrorList(
[_("Invalid application config value")]
)
return self.cleaned_data
if self._check_unique_namespace_instance(config.namespace):
# Looks like there's already one with the default instance
# namespace defined.
self._errors["application_configs"] = ErrorList(
[
_(
"An application instance using this configuration already exists."
)
]
)
else:
self.cleaned_data["application_namespace"] = config.namespace
else:
if instance_namespace:
if self._check_unique_namespace_instance(instance_namespace):
self._errors["application_namespace"] = ErrorList(
[
_(
"An application instance with this name already exists."
)
]
)
else:
# The attribute on the apps 'app_name' is a misnomer, it should be
# 'application_namespace'.
application_namespace = apphook_pool.get_apphook(apphook).app_name
if application_namespace and not instance_namespace:
if self._check_unique_namespace_instance(application_namespace):
# Looks like there's already one with the default instance
# namespace defined.
self._errors["application_namespace"] = ErrorList(
[
_(
"An application instance with this name already exists."
)
]
)
else:
# OK, there are zero instances of THIS app that use the
# default instance namespace, so, since the user didn't
# provide one, we'll use the default. NOTE: The following
# line is really setting the "instance namespace" of the
# new app to the app’s "application namespace", which is
# the default instance namespace.
self.cleaned_data["application_namespace"] = (
application_namespace
)
if instance_namespace and not apphook:
self.cleaned_data["application_namespace"] = None
if application_config and not apphook:
self.cleaned_data["application_configs"] = None
return self.cleaned_data
def get_apphooks(self):
for hook in apphook_pool.get_apphooks():
yield (hook[0], apphook_pool.get_apphook(hook[0]))
def get_apphooks_with_config(self):
return {key: app for key, app in self.get_apphooks() if app.app_config}
def get_navigation_extenders(self):
return menu_pool.get_menus_by_attribute("cms_enabled", True)
def _check_unique_namespace_instance(self, namespace):
return (
Page.objects.on_site(self._site)
.filter(application_namespace=namespace)
.exclude(pk=self.instance.pk)
.exists()
)
def has_changed_apphooks(self):
changed_data = self.changed_data
if "application_urls" in changed_data:
return True
return "application_namespace" in changed_data
def save(self, *args, **kwargs):
page = super().save(*args, **kwargs)
page.clear_cache(menu=True)
clear_permission_cache()
if self.has_changed_apphooks():
set_restart_trigger()
return page
class PageTreeForm(forms.Form):
position = forms.IntegerField(initial=0, required=True)
target = forms.ModelChoiceField(queryset=Page.objects.none(), required=False)
def __init__(self, *args, **kwargs):
self.page = kwargs.pop("page")
self._site = kwargs.pop("site", Site.objects.get_current())
super().__init__(*args, **kwargs)
self.fields["target"].queryset = Page.objects.filter(
node__site=self._site,
is_page_type=self.page.is_page_type,
)
def get_root_nodes(self):
# TODO: this needs to avoid using the pages accessor directly
nodes = TreeNode.get_root_nodes()
return nodes.exclude(cms_pages__is_page_type=not self.page.is_page_type)
def get_tree_options(self):
position = self.cleaned_data["position"]
target_page = self.cleaned_data.get("target")
parent_node = target_page.node if target_page else None
if parent_node:
return self._get_tree_options_for_parent(parent_node, position)
return self._get_tree_options_for_root(position)
def _get_tree_options_for_root(self, position):
siblings = self.get_root_nodes().filter(site=self._site)
try:
target_node = siblings[position]
except IndexError:
# The position requested is not occupied.
# Add the node as the last root node,
# relative to the current site.
return (siblings.reverse()[0], "right")
return (target_node, "left")
def _get_tree_options_for_parent(self, parent_node, position):
if position == 0:
return (parent_node, "first-child")
siblings = parent_node.get_children().filter(site=self._site)
try:
target_node = siblings[position]
except IndexError:
# The position requested is not occupied.
# Add the node to be the parent's first child
return (parent_node, "last-child")
return (target_node, "left")
class MovePageForm(PageTreeForm):
def clean(self):
cleaned_data = super().clean()
if self.page.is_home and cleaned_data.get("target"):
self.add_error(
"target",
force_str(_("You can't move the home page inside another page")),
)
return cleaned_data
def get_tree_options(self):
options = super().get_tree_options()
target_node, target_node_position = options
if target_node_position != "left":
return (target_node, target_node_position)
node = self.page.node
node_is_first = node.path < target_node.path
if node_is_first and node.is_sibling_of(target_node):
# The node being moved appears before the target node
# and is a sibling of the target node.