-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
models.py
2019 lines (1658 loc) · 76.6 KB
/
models.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
import json
import logging
from collections import defaultdict
from io import StringIO
from urllib.parse import urlparse
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core import checks
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.handlers.base import BaseHandler
from django.core.handlers.wsgi import WSGIRequest
from django.db import models, transaction
from django.db.models import Q, Value
from django.db.models.functions import Concat, Substr
from django.http import Http404
from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.text import capfirst, slugify
from django.utils.translation import ugettext_lazy as _
from modelcluster.models import ClusterableModel, get_all_child_relations
from treebeard.mp_tree import MP_Node
from wagtail.core.query import PageQuerySet, TreeQuerySet
from wagtail.core.signals import page_published, page_unpublished
from wagtail.core.sites import get_site_for_hostname
from wagtail.core.url_routing import RouteResult
from wagtail.core.utils import WAGTAIL_APPEND_SLASH, camelcase_to_underscore, resolve_model_string
from wagtail.search import index
logger = logging.getLogger('wagtail.core')
PAGE_TEMPLATE_VAR = 'page'
class SiteManager(models.Manager):
def get_by_natural_key(self, hostname, port):
return self.get(hostname=hostname, port=port)
class Site(models.Model):
hostname = models.CharField(verbose_name=_('hostname'), max_length=255, db_index=True)
port = models.IntegerField(
verbose_name=_('port'),
default=80,
help_text=_(
"Set this to something other than 80 if you need a specific port number to appear in URLs"
" (e.g. development on port 8000). Does not affect request handling (so port forwarding still works)."
)
)
site_name = models.CharField(
verbose_name=_('site name'),
max_length=255,
null=True,
blank=True,
help_text=_("Human-readable name for the site.")
)
root_page = models.ForeignKey('Page', verbose_name=_('root page'), related_name='sites_rooted_here', on_delete=models.CASCADE)
is_default_site = models.BooleanField(
verbose_name=_('is default site'),
default=False,
help_text=_(
"If true, this site will handle requests for all other hostnames that do not have a site entry of their own"
)
)
objects = SiteManager()
class Meta:
unique_together = ('hostname', 'port')
verbose_name = _('site')
verbose_name_plural = _('sites')
def natural_key(self):
return (self.hostname, self.port)
def __str__(self):
if self.site_name:
return(
self.site_name +
(" [default]" if self.is_default_site else "")
)
else:
return(
self.hostname +
("" if self.port == 80 else (":%d" % self.port)) +
(" [default]" if self.is_default_site else "")
)
@staticmethod
def find_for_request(request):
"""
Find the site object responsible for responding to this HTTP
request object. Try:
* unique hostname first
* then hostname and port
* if there is no matching hostname at all, or no matching
hostname:port combination, fall back to the unique default site,
or raise an exception
NB this means that high-numbered ports on an extant hostname may
still be routed to a different hostname which is set as the default
"""
try:
hostname = request.get_host().split(':')[0]
except KeyError:
hostname = None
try:
port = request.get_port()
except (AttributeError, KeyError):
port = request.META.get('SERVER_PORT')
return get_site_for_hostname(hostname, port)
@property
def root_url(self):
if self.port == 80:
return 'http://%s' % self.hostname
elif self.port == 443:
return 'https://%s' % self.hostname
else:
return 'http://%s:%d' % (self.hostname, self.port)
def clean_fields(self, exclude=None):
super().clean_fields(exclude)
# Only one site can have the is_default_site flag set
try:
default = Site.objects.get(is_default_site=True)
except Site.DoesNotExist:
pass
except Site.MultipleObjectsReturned:
raise
else:
if self.is_default_site and self.pk != default.pk:
raise ValidationError(
{'is_default_site': [
_(
"%(hostname)s is already configured as the default site."
" You must unset that before you can save this site as default."
)
% {'hostname': default.hostname}
]}
)
@staticmethod
def get_site_root_paths():
"""
Return a list of (root_path, root_url) tuples, most specific path first -
used to translate url_paths into actual URLs with hostnames
"""
result = cache.get('wagtail_site_root_paths')
if result is None:
result = [
(site.id, site.root_page.url_path, site.root_url)
for site in Site.objects.select_related('root_page').order_by('-root_page__url_path')
]
cache.set('wagtail_site_root_paths', result, 3600)
return result
PAGE_MODEL_CLASSES = []
def get_page_models():
"""
Returns a list of all non-abstract Page model classes defined in this project.
"""
return PAGE_MODEL_CLASSES
def get_default_page_content_type():
"""
Returns the content type to use as a default for pages whose content type
has been deleted.
"""
return ContentType.objects.get_for_model(Page)
class BasePageManager(models.Manager):
def get_queryset(self):
return self._queryset_class(self.model).order_by('path')
PageManager = BasePageManager.from_queryset(PageQuerySet)
class PageBase(models.base.ModelBase):
"""Metaclass for Page"""
def __init__(cls, name, bases, dct):
super(PageBase, cls).__init__(name, bases, dct)
if 'template' not in dct:
# Define a default template path derived from the app name and model name
cls.template = "%s/%s.html" % (cls._meta.app_label, camelcase_to_underscore(name))
if 'ajax_template' not in dct:
cls.ajax_template = None
cls._clean_subpage_models = None # to be filled in on first call to cls.clean_subpage_models
cls._clean_parent_page_models = None # to be filled in on first call to cls.clean_parent_page_models
# All pages should be creatable unless explicitly set otherwise.
# This attribute is not inheritable.
if 'is_creatable' not in dct:
cls.is_creatable = not cls._meta.abstract
if not cls._meta.abstract:
# register this type in the list of page content types
PAGE_MODEL_CLASSES.append(cls)
class AbstractPage(MP_Node):
"""
Abstract superclass for Page. According to Django's inheritance rules, managers set on
abstract models are inherited by subclasses, but managers set on concrete models that are extended
via multi-table inheritance are not. We therefore need to attach PageManager to an abstract
superclass to ensure that it is retained by subclasses of Page.
"""
objects = PageManager()
class Meta:
abstract = True
class Page(AbstractPage, index.Indexed, ClusterableModel, metaclass=PageBase):
title = models.CharField(
verbose_name=_('title'),
max_length=255,
help_text=_("The page title as you'd like it to be seen by the public")
)
# to reflect title of a current draft in the admin UI
draft_title = models.CharField(
max_length=255,
editable=False
)
slug = models.SlugField(
verbose_name=_('slug'),
allow_unicode=True,
max_length=255,
help_text=_("The name of the page as it will appear in URLs e.g http://domain.com/blog/[my-slug]/")
)
content_type = models.ForeignKey(
'contenttypes.ContentType',
verbose_name=_('content type'),
related_name='pages',
on_delete=models.SET(get_default_page_content_type)
)
live = models.BooleanField(verbose_name=_('live'), default=True, editable=False)
has_unpublished_changes = models.BooleanField(
verbose_name=_('has unpublished changes'),
default=False,
editable=False
)
url_path = models.TextField(verbose_name=_('URL path'), blank=True, editable=False)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
verbose_name=_('owner'),
null=True,
blank=True,
editable=True,
on_delete=models.SET_NULL,
related_name='owned_pages'
)
seo_title = models.CharField(
verbose_name=_("page title"),
max_length=255,
blank=True,
help_text=_("Optional. 'Search Engine Friendly' title. This will appear at the top of the browser window.")
)
show_in_menus_default = False
show_in_menus = models.BooleanField(
verbose_name=_('show in menus'),
default=False,
help_text=_("Whether a link to this page will appear in automatically generated menus")
)
search_description = models.TextField(verbose_name=_('search description'), blank=True)
go_live_at = models.DateTimeField(
verbose_name=_("go live date/time"),
blank=True,
null=True
)
expire_at = models.DateTimeField(
verbose_name=_("expiry date/time"),
blank=True,
null=True
)
expired = models.BooleanField(verbose_name=_('expired'), default=False, editable=False)
locked = models.BooleanField(verbose_name=_('locked'), default=False, editable=False)
first_published_at = models.DateTimeField(
verbose_name=_('first published at'),
blank=True,
null=True,
db_index=True
)
last_published_at = models.DateTimeField(
verbose_name=_('last published at'),
null=True,
editable=False
)
latest_revision_created_at = models.DateTimeField(
verbose_name=_('latest revision created at'),
null=True,
editable=False
)
live_revision = models.ForeignKey(
'PageRevision',
related_name='+',
verbose_name='live revision',
on_delete=models.SET_NULL,
null=True,
blank=True,
editable=False
)
search_fields = [
index.SearchField('title', partial_match=True, boost=2),
index.FilterField('title'),
index.FilterField('id'),
index.FilterField('live'),
index.FilterField('owner'),
index.FilterField('content_type'),
index.FilterField('path'),
index.FilterField('depth'),
index.FilterField('locked'),
index.FilterField('show_in_menus'),
index.FilterField('first_published_at'),
index.FilterField('last_published_at'),
index.FilterField('latest_revision_created_at'),
]
# Do not allow plain Page instances to be created through the Wagtail admin
is_creatable = False
# An array of additional field names that will not be included when a Page is copied.
exclude_fields_in_copy = []
# Define these attributes early to avoid masking errors. (Issue #3078)
# The canonical definition is in wagtailadmin.edit_handlers.
content_panels = []
promote_panels = []
settings_panels = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.id:
# this model is being newly created
# rather than retrieved from the db;
if not self.content_type_id:
# set content type to correctly represent the model class
# that this was created as
self.content_type = ContentType.objects.get_for_model(self)
if 'show_in_menus' not in kwargs:
# if the value is not set on submit refer to the model setting
self.show_in_menus = self.show_in_menus_default
def __str__(self):
return self.title
def set_url_path(self, parent):
"""
Populate the url_path field based on this page's slug and the specified parent page.
(We pass a parent in here, rather than retrieving it via get_parent, so that we can give
new unsaved pages a meaningful URL when previewing them; at that point the page has not
been assigned a position in the tree, as far as treebeard is concerned.
"""
if parent:
self.url_path = parent.url_path + self.slug + '/'
else:
# a page without a parent is the tree root, which always has a url_path of '/'
self.url_path = '/'
return self.url_path
@staticmethod
def _slug_is_available(slug, parent_page, page=None):
"""
Determine whether the given slug is available for use on a child page of
parent_page. If 'page' is passed, the slug is intended for use on that page
(and so it will be excluded from the duplicate check).
"""
if parent_page is None:
# the root page's slug can be whatever it likes...
return True
siblings = parent_page.get_children()
if page:
siblings = siblings.not_page(page)
return not siblings.filter(slug=slug).exists()
def _get_autogenerated_slug(self, base_slug):
candidate_slug = base_slug
suffix = 1
parent_page = self.get_parent()
while not Page._slug_is_available(candidate_slug, parent_page, self):
# try with incrementing suffix until we find a slug which is available
suffix += 1
candidate_slug = "%s-%d" % (base_slug, suffix)
return candidate_slug
def full_clean(self, *args, **kwargs):
# Apply fixups that need to happen before per-field validation occurs
if not self.slug:
# Try to auto-populate slug from title
base_slug = slugify(self.title, allow_unicode=True)
# only proceed if we get a non-empty base slug back from slugify
if base_slug:
self.slug = self._get_autogenerated_slug(base_slug)
if not self.draft_title:
self.draft_title = self.title
super().full_clean(*args, **kwargs)
def clean(self):
super().clean()
if not Page._slug_is_available(self.slug, self.get_parent(), self):
raise ValidationError({'slug': _("This slug is already in use")})
@transaction.atomic
# ensure that changes are only committed when we have updated all descendant URL paths, to preserve consistency
def save(self, *args, **kwargs):
self.full_clean()
update_descendant_url_paths = False
is_new = self.id is None
if is_new:
# we are creating a record. If we're doing things properly, this should happen
# through a treebeard method like add_child, in which case the 'path' field
# has been set and so we can safely call get_parent
self.set_url_path(self.get_parent())
else:
# Check that we are committing the slug to the database
# Basically: If update_fields has been specified, and slug is not included, skip this step
if not ('update_fields' in kwargs and 'slug' not in kwargs['update_fields']):
# see if the slug has changed from the record in the db, in which case we need to
# update url_path of self and all descendants
old_record = Page.objects.get(id=self.id)
if old_record.slug != self.slug:
self.set_url_path(self.get_parent())
update_descendant_url_paths = True
old_url_path = old_record.url_path
new_url_path = self.url_path
result = super().save(*args, **kwargs)
if update_descendant_url_paths:
self._update_descendant_url_paths(old_url_path, new_url_path)
# Check if this is a root page of any sites and clear the 'wagtail_site_root_paths' key if so
if Site.objects.filter(root_page=self).exists():
cache.delete('wagtail_site_root_paths')
# Log
if is_new:
cls = type(self)
logger.info(
"Page created: \"%s\" id=%d content_type=%s.%s path=%s",
self.title,
self.id,
cls._meta.app_label,
cls.__name__,
self.url_path
)
return result
def delete(self, *args, **kwargs):
# Ensure that deletion always happens on an instance of Page, not a specific subclass. This
# works around a bug in treebeard <= 3.0 where calling SpecificPage.delete() fails to delete
# child pages that are not instances of SpecificPage
if type(self) is Page:
# this is a Page instance, so carry on as we were
return super().delete(*args, **kwargs)
else:
# retrieve an actual Page instance and delete that instead of self
return Page.objects.get(id=self.id).delete(*args, **kwargs)
@classmethod
def check(cls, **kwargs):
errors = super(Page, cls).check(**kwargs)
# Check that foreign keys from pages are not configured to cascade
# This is the default Django behaviour which must be explicitly overridden
# to prevent pages disappearing unexpectedly and the tree being corrupted
# get names of foreign keys pointing to parent classes (such as page_ptr)
field_exceptions = [field.name
for model in [cls] + list(cls._meta.get_parent_list())
for field in model._meta.parents.values() if field]
for field in cls._meta.fields:
if isinstance(field, models.ForeignKey) and field.name not in field_exceptions:
if field.remote_field.on_delete == models.CASCADE:
errors.append(
checks.Warning(
"Field hasn't specified on_delete action",
hint="Set on_delete=models.SET_NULL and make sure the field is nullable or set on_delete=models.PROTECT. Wagtail does not allow simple database CASCADE because it will corrupt its tree storage.",
obj=field,
id='wagtailcore.W001',
)
)
if not isinstance(cls.objects, PageManager):
errors.append(
checks.Error(
"Manager does not inherit from PageManager",
hint="Ensure that custom Page managers inherit from wagtail.core.models.PageManager",
obj=cls,
id='wagtailcore.E002',
)
)
try:
cls.clean_subpage_models()
except (ValueError, LookupError) as e:
errors.append(
checks.Error(
"Invalid subpage_types setting for %s" % cls,
hint=str(e),
id='wagtailcore.E002'
)
)
try:
cls.clean_parent_page_models()
except (ValueError, LookupError) as e:
errors.append(
checks.Error(
"Invalid parent_page_types setting for %s" % cls,
hint=str(e),
id='wagtailcore.E002'
)
)
return errors
def _update_descendant_url_paths(self, old_url_path, new_url_path):
(Page.objects
.filter(path__startswith=self.path)
.exclude(pk=self.pk)
.update(url_path=Concat(
Value(new_url_path),
Substr('url_path', len(old_url_path) + 1))))
#: Return this page in its most specific subclassed form.
@cached_property
def specific(self):
"""
Return this page in its most specific subclassed form.
"""
# the ContentType.objects manager keeps a cache, so this should potentially
# avoid a database lookup over doing self.content_type. I think.
content_type = ContentType.objects.get_for_id(self.content_type_id)
model_class = content_type.model_class()
if model_class is None:
# Cannot locate a model class for this content type. This might happen
# if the codebase and database are out of sync (e.g. the model exists
# on a different git branch and we haven't rolled back migrations before
# switching branches); if so, the best we can do is return the page
# unchanged.
return self
elif isinstance(self, model_class):
# self is already the an instance of the most specific class
return self
else:
return content_type.get_object_for_this_type(id=self.id)
#: Return the class that this page would be if instantiated in its
#: most specific form
@cached_property
def specific_class(self):
"""
Return the class that this page would be if instantiated in its
most specific form
"""
content_type = ContentType.objects.get_for_id(self.content_type_id)
return content_type.model_class()
def route(self, request, path_components):
if path_components:
# request is for a child of this page
child_slug = path_components[0]
remaining_components = path_components[1:]
try:
subpage = self.get_children().get(slug=child_slug)
except Page.DoesNotExist:
raise Http404
return subpage.specific.route(request, remaining_components)
else:
# request is for this very page
if self.live:
return RouteResult(self)
else:
raise Http404
def get_admin_display_title(self):
"""
Return the title for this page as it should appear in the admin backend;
override this if you wish to display extra contextual information about the page,
such as language. By default, returns ``draft_title``.
"""
# Fall back on title if draft_title is blank (which may happen if the page was created
# in a fixture or migration that didn't explicitly handle draft_title)
return self.draft_title or self.title
def save_revision(self, user=None, submitted_for_moderation=False, approved_go_live_at=None, changed=True):
self.full_clean()
# Create revision
revision = self.revisions.create(
content_json=self.to_json(),
user=user,
submitted_for_moderation=submitted_for_moderation,
approved_go_live_at=approved_go_live_at,
)
update_fields = []
self.latest_revision_created_at = revision.created_at
update_fields.append('latest_revision_created_at')
self.draft_title = self.title
update_fields.append('draft_title')
if changed:
self.has_unpublished_changes = True
update_fields.append('has_unpublished_changes')
if update_fields:
self.save(update_fields=update_fields)
# Log
logger.info("Page edited: \"%s\" id=%d revision_id=%d", self.title, self.id, revision.id)
if submitted_for_moderation:
logger.info("Page submitted for moderation: \"%s\" id=%d revision_id=%d", self.title, self.id, revision.id)
return revision
def get_latest_revision(self):
return self.revisions.order_by('-created_at', '-id').first()
def get_latest_revision_as_page(self):
if not self.has_unpublished_changes:
# Use the live database copy in preference to the revision record, as:
# 1) this will pick up any changes that have been made directly to the model,
# such as automated data imports;
# 2) it ensures that inline child objects pick up real database IDs even if
# those are absent from the revision data. (If this wasn't the case, the child
# objects would be recreated with new IDs on next publish - see #1853)
return self.specific
latest_revision = self.get_latest_revision()
if latest_revision:
return latest_revision.as_page_object()
else:
return self.specific
def unpublish(self, set_expired=False, commit=True):
if self.live:
self.live = False
self.has_unpublished_changes = True
self.live_revision = None
if set_expired:
self.expired = True
if commit:
self.save()
page_unpublished.send(sender=self.specific_class, instance=self.specific)
logger.info("Page unpublished: \"%s\" id=%d", self.title, self.id)
self.revisions.update(approved_go_live_at=None)
def get_context(self, request, *args, **kwargs):
return {
PAGE_TEMPLATE_VAR: self,
'self': self,
'request': request,
}
def get_template(self, request, *args, **kwargs):
if request.is_ajax():
return self.ajax_template or self.template
else:
return self.template
def serve(self, request, *args, **kwargs):
request.is_preview = getattr(request, 'is_preview', False)
return TemplateResponse(
request,
self.get_template(request, *args, **kwargs),
self.get_context(request, *args, **kwargs)
)
def is_navigable(self):
"""
Return true if it's meaningful to browse subpages of this page -
i.e. it currently has subpages,
or it's at the top level (this rule necessary for empty out-of-the-box sites to have working navigation)
"""
return (not self.is_leaf()) or self.depth == 2
def _get_site_root_paths(self, request=None):
"""
Return ``Site.get_site_root_paths()``, using the cached copy on the
request object if available.
"""
# if we have a request, use that to cache site_root_paths; otherwise, use self
cache_object = request if request else self
try:
return cache_object._wagtail_cached_site_root_paths
except AttributeError:
cache_object._wagtail_cached_site_root_paths = Site.get_site_root_paths()
return cache_object._wagtail_cached_site_root_paths
def get_url_parts(self, request=None):
"""
Determine the URL for this page and return it as a tuple of
``(site_id, site_root_url, page_url_relative_to_site_root)``.
Return None if the page is not routable.
This is used internally by the ``full_url``, ``url``, ``relative_url``
and ``get_site`` properties and methods; pages with custom URL routing
should override this method in order to have those operations return
the custom URLs.
Accepts an optional keyword argument ``request``, which may be used
to avoid repeated database / cache lookups. Typically, a page model
that overrides ``get_url_parts`` should not need to deal with
``request`` directly, and should just pass it to the original method
when calling ``super``.
"""
for (site_id, root_path, root_url) in self._get_site_root_paths(request):
if self.url_path.startswith(root_path):
page_path = reverse('wagtail_serve', args=(self.url_path[len(root_path):],))
# Remove the trailing slash from the URL reverse generates if
# WAGTAIL_APPEND_SLASH is False and we're not trying to serve
# the root path
if not WAGTAIL_APPEND_SLASH and page_path != '/':
page_path = page_path.rstrip('/')
return (site_id, root_url, page_path)
def get_full_url(self, request=None):
"""Return the full URL (including protocol / domain) to this page, or None if it is not routable"""
url_parts = self.get_url_parts(request=request)
if url_parts is None:
# page is not routable
return
site_id, root_url, page_path = url_parts
return root_url + page_path
full_url = property(get_full_url)
def get_url(self, request=None, current_site=None):
"""
Return the 'most appropriate' URL for referring to this page from the pages we serve,
within the Wagtail backend and actual website templates;
this is the local URL (starting with '/') if we're only running a single site
(i.e. we know that whatever the current page is being served from, this link will be on the
same domain), and the full URL (with domain) if not.
Return None if the page is not routable.
Accepts an optional but recommended ``request`` keyword argument that, if provided, will
be used to cache site-level URL information (thereby avoiding repeated database / cache
lookups) and, via the ``request.site`` attribute, determine whether a relative or full URL
is most appropriate.
"""
# ``current_site`` is purposefully undocumented, as one can simply pass the request and get
# a relative URL based on ``request.site``. Nonetheless, support it here to avoid
# copy/pasting the code to the ``relative_url`` method below.
if current_site is None and request is not None:
current_site = getattr(request, 'site', None)
url_parts = self.get_url_parts(request=request)
if url_parts is None:
# page is not routable
return
site_id, root_url, page_path = url_parts
if (current_site is not None and site_id == current_site.id) or len(self._get_site_root_paths(request)) == 1:
# the site matches OR we're only running a single site, so a local URL is sufficient
return page_path
else:
return root_url + page_path
url = property(get_url)
def relative_url(self, current_site, request=None):
"""
Return the 'most appropriate' URL for this page taking into account the site we're currently on;
a local URL if the site matches, or a fully qualified one otherwise.
Return None if the page is not routable.
Accepts an optional but recommended ``request`` keyword argument that, if provided, will
be used to cache site-level URL information (thereby avoiding repeated database / cache
lookups).
"""
return self.get_url(request=request, current_site=current_site)
def get_site(self):
"""
Return the Site object that this page belongs to.
"""
url_parts = self.get_url_parts()
if url_parts is None:
# page is not routable
return
site_id, root_url, page_path = url_parts
return Site.objects.get(id=site_id)
@classmethod
def get_indexed_objects(cls):
content_type = ContentType.objects.get_for_model(cls)
return super(Page, cls).get_indexed_objects().filter(content_type=content_type)
def get_indexed_instance(self):
# This is accessed on save by the wagtailsearch signal handler, and in edge
# cases (e.g. loading test fixtures), may be called before the specific instance's
# entry has been created. In those cases, we aren't ready to be indexed yet, so
# return None.
try:
return self.specific
except self.specific_class.DoesNotExist:
return None
@classmethod
def clean_subpage_models(cls):
"""
Returns the list of subpage types, normalised as model classes.
Throws ValueError if any entry in subpage_types cannot be recognised as a model name,
or LookupError if a model does not exist (or is not a Page subclass).
"""
if cls._clean_subpage_models is None:
subpage_types = getattr(cls, 'subpage_types', None)
if subpage_types is None:
# if subpage_types is not specified on the Page class, allow all page types as subpages
cls._clean_subpage_models = get_page_models()
else:
cls._clean_subpage_models = [
resolve_model_string(model_string, cls._meta.app_label)
for model_string in subpage_types
]
for model in cls._clean_subpage_models:
if not issubclass(model, Page):
raise LookupError("%s is not a Page subclass" % model)
return cls._clean_subpage_models
@classmethod
def clean_parent_page_models(cls):
"""
Returns the list of parent page types, normalised as model classes.
Throws ValueError if any entry in parent_page_types cannot be recognised as a model name,
or LookupError if a model does not exist (or is not a Page subclass).
"""
if cls._clean_parent_page_models is None:
parent_page_types = getattr(cls, 'parent_page_types', None)
if parent_page_types is None:
# if parent_page_types is not specified on the Page class, allow all page types as subpages
cls._clean_parent_page_models = get_page_models()
else:
cls._clean_parent_page_models = [
resolve_model_string(model_string, cls._meta.app_label)
for model_string in parent_page_types
]
for model in cls._clean_parent_page_models:
if not issubclass(model, Page):
raise LookupError("%s is not a Page subclass" % model)
return cls._clean_parent_page_models
@classmethod
def allowed_parent_page_models(cls):
"""
Returns the list of page types that this page type can be a subpage of,
as a list of model classes
"""
return [
parent_model for parent_model in cls.clean_parent_page_models()
if cls in parent_model.clean_subpage_models()
]
@classmethod
def allowed_subpage_models(cls):
"""
Returns the list of page types that this page type can have as subpages,
as a list of model classes
"""
return [
subpage_model for subpage_model in cls.clean_subpage_models()
if cls in subpage_model.clean_parent_page_models()
]
@classmethod
def creatable_subpage_models(cls):
"""
Returns the list of page types that may be created under this page type,
as a list of model classes
"""
return [
page_model for page_model in cls.allowed_subpage_models()
if page_model.is_creatable
]
@classmethod
def can_exist_under(cls, parent):
"""
Checks if this page type can exist as a subpage under a parent page
instance.
See also: :func:`Page.can_create_at` and :func:`Page.can_move_to`
"""
return cls in parent.specific_class.allowed_subpage_models()
@classmethod
def can_create_at(cls, parent):
"""
Checks if this page type can be created as a subpage under a parent
page instance.
"""
return cls.is_creatable and cls.can_exist_under(parent)
def can_move_to(self, parent):
"""
Checks if this page instance can be moved to be a subpage of a parent
page instance.
"""
return self.can_exist_under(parent)
@classmethod
def get_verbose_name(cls):
"""
Returns the human-readable "verbose name" of this page model e.g "Blog page".
"""
# This is similar to doing cls._meta.verbose_name.title()
# except this doesn't convert any characters to lowercase
return capfirst(cls._meta.verbose_name)
@property
def status_string(self):
if not self.live:
if self.expired:
return _("expired")
elif self.approved_schedule:
return _("scheduled")
else:
return _("draft")
else:
if self.approved_schedule:
return _("live + scheduled")
elif self.has_unpublished_changes:
return _("live + draft")
else:
return _("live")
@property
def approved_schedule(self):
return self.revisions.exclude(approved_go_live_at__isnull=True).exists()