/
abstract_content_model.py
516 lines (438 loc) · 20.4 KB
/
abstract_content_model.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
from __future__ import annotations
import logging
from copy import copy
from typing import TYPE_CHECKING
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.translation import get_language
from django.utils.translation import gettext_lazy as _
if TYPE_CHECKING:
from typing import Any, Iterator
from .languages.language import Language
from .abstract_content_translation import AbstractContentTranslation
from ..constants import status, translation_status
from ..utils.content_edit_lock import get_locking_user
from .abstract_base_model import AbstractBaseModel
from .regions.region import Region
logger = logging.getLogger(__name__)
class ContentQuerySet(models.QuerySet):
"""
This queryset provides the option to prefetch translations for content objects
"""
def prefetch_translations(
self, to_attr: str = "prefetched_translations", **filters: Any
) -> ContentQuerySet:
r"""
Get the queryset including the custom attribute ``to_attr`` which contains the latest
translations of each content object in each language, optionally filtered by the given ``status``
:param to_attr: To which attribute the prefetched translations should be added [optional, defaults to ``prefetched_translations``]
:param \**filters: Additional filters to be applied on the translations (e.g. by status)
:return: The queryset of content objects
"""
TranslationModel = self.model.get_translation_model()
foreign_field = TranslationModel.foreign_field() + "_id"
return self.prefetch_related(
models.Prefetch(
"translations",
queryset=TranslationModel.objects.filter(**filters)
.order_by(foreign_field, "language_id", "-version")
.distinct(foreign_field, "language_id")
.select_related("language"),
to_attr=to_attr,
)
)
def prefetch_public_translations(
self,
) -> ContentQuerySet:
"""
Get the queryset including the custom attribute ``prefetched_public_translations`` which contains the latest
public translations of each content object in each language
:return: The queryset of content objects
"""
return self.prefetch_translations(
to_attr="prefetched_public_translations", status=status.PUBLIC
)
def prefetch_public_or_draft_translations(
self,
) -> ContentQuerySet:
"""
Get the queryset including the custom attribute ``prefetched_public_or_draft_translations`` which contains the latest
public or draft translations of each content object in each language
:return: The queryset of content objects
"""
return self.prefetch_translations(
to_attr="prefetched_public_or_draft_translations",
status__in=[status.DRAFT, status.PUBLIC],
)
def prefetch_major_translations(self) -> ContentQuerySet:
"""
Get the queryset including the custom attribute ``prefetched_major_translations`` which contains the
latest major (in other words not a minor edit) translations of each content object in each language
:return: The queryset of content objects
"""
return self.prefetch_translations(
to_attr="prefetched_major_translations",
minor_edit=False,
)
def prefetch_major_public_translations(
self,
) -> ContentQuerySet:
"""
Get the queryset including the custom attribute ``prefetched_major_public_translations`` which contains the
latest major (in other words not a minor edit) public translations of each content object in each language
:return: The queryset of content objects
"""
return self.prefetch_translations(
to_attr="prefetched_major_public_translations",
status=status.PUBLIC,
minor_edit=False,
)
# pylint: disable=too-many-public-methods
class AbstractContentModel(AbstractBaseModel):
"""
Abstract base class for all content models
"""
region = models.ForeignKey(
Region, on_delete=models.CASCADE, verbose_name=_("region")
)
created_date = models.DateTimeField(
default=timezone.now, verbose_name=_("creation date")
)
#: Custom model manager for content objects
objects = ContentQuerySet.as_manager()
#: Whether the HIX value is ignored (this is ``False`` by default if not overwritten by a submodel)
hix_ignore: bool = False
@property
def fallback_translations_enabled(self) -> bool:
"""
Whether translations should be returned in the default language if they do not exist
:return: Whether fallback translations are enabled
"""
return False
@cached_property
def languages(self) -> list[Language]:
"""
This property returns a list of all :class:`~integreat_cms.cms.models.languages.language.Language` objects, to
which a translation exists.
:return: The existing languages of this content object
"""
translations = self.prefetched_translations_by_language_slug.values()
return [translation.language for translation in translations]
def available_translations(self) -> Iterator[Any]:
"""
This method returns an iterator over all available translations, respecting the `fallback_translations_enabled` setting.
:return: An iterator over all translations
"""
# Check if fallback translation should be used
all_languages = (
self.region.visible_languages
if self.fallback_translations_enabled
else self.public_languages
)
for language in all_languages:
if public_translation := self.get_public_translation(language.slug):
yield public_translation
@cached_property
def public_languages(self) -> list[Language]:
"""
This property returns a list of all :class:`~integreat_cms.cms.models.languages.language.Language` objects, to
which a public translation exists and which are visible in this region.
:return: The existing languages of this content object
"""
translations = self.prefetched_public_translations_by_language_slug.values()
return [
translation.language
for translation in translations
if translation.language in self.region.visible_languages
]
def get_prefetched_translations_by_language_slug(
self, attr: str = "prefetched_translations", **filters: Any
) -> dict[str, AbstractContentTranslation]:
r"""
This method returns a mapping from language slugs to their latest translations of this object
:param attr: Which attribute should be tried to get the prefetched translations [optional, defaults to ``"prefetched_translations"``]
:param \**filters: Additional filters to be applied on the translations (e.g. by status)
:return: The prefetched translations by language slug
"""
if not self.id:
return {}
try:
# Try to get the prefetched translations (which are already distinct per language)
prefetched_translations = getattr(self, attr)
except AttributeError:
# If the translations were not prefetched, query it from the database
prefetched_translations = (
self.translations.filter(**filters)
.select_related("language")
.order_by("language__id", "-version")
.distinct("language__id")
.all()
)
return {
translation.language.slug: translation
for translation in prefetched_translations
}
@cached_property
def prefetched_translations_by_language_slug(
self,
) -> dict[str, AbstractContentTranslation]:
"""
This method returns a mapping from language slugs to their latest translations of this object
:return: The prefetched translations by language slug
"""
return self.get_prefetched_translations_by_language_slug()
def get_translation(self, language_slug: str) -> AbstractContentTranslation | None:
"""
This function uses the reverse foreign key ``self.translations`` to get all translations of ``self``
and filters them to the requested :class:`~integreat_cms.cms.models.languages.language.Language` slug.
:param language_slug: The slug of the desired :class:`~integreat_cms.cms.models.languages.language.Language`
:return: The translation in the requested :class:`~integreat_cms.cms.models.languages.language.Language` or
:obj:`None` if no translation exists
"""
return self.prefetched_translations_by_language_slug.get(language_slug)
@cached_property
def prefetched_public_translations_by_language_slug(
self,
) -> dict[str, AbstractContentTranslation]:
"""
This method returns a mapping from language slugs to their public translations of this object
:return: The object translation in the requested :class:`~integreat_cms.cms.models.languages.language.Language` or
:obj:`None` if no translation exists
"""
return self.get_prefetched_translations_by_language_slug(
attr="prefetched_public_translations", status=status.PUBLIC
)
def get_public_translation(
self, language_slug: str
) -> AbstractContentTranslation | None:
"""
This function retrieves the newest public translation of a content object.
:param language_slug: The slug of the requested :class:`~integreat_cms.cms.models.languages.language.Language`
:return: The public translation of a content object
"""
public_translation = self.prefetched_public_translations_by_language_slug.get(
language_slug
)
# Check if fallback translation should be used
if not public_translation and self.fallback_translations_enabled:
# Get the fallback translation
public_translation = (
self.prefetched_public_translations_by_language_slug.get(
self.region.default_language.slug
)
)
if public_translation:
public_translation = copy(public_translation)
public_translation.read_only = True
# Reset id to make sure id does not conflict with existing translation
public_translation.id = None
# Fake the requested language
public_translation.language = self.region.language_node_by_slug[
language_slug
].language
# Reset prefetched translations
public_translation.foreign_object.prefetched_public_translations_by_language_slug = (
self.prefetched_public_translations_by_language_slug
)
# Clear cached property in case url with different language was already calculated before
try:
del public_translation.url_prefix
except AttributeError:
pass
return public_translation
@cached_property
def prefetched_public_or_draft_translations_by_language_slug(
self,
) -> dict[str, AbstractContentTranslation]:
"""
This method returns a mapping from language slugs to their public translations of this object
:return: The object translation in the requested :class:`~integreat_cms.cms.models.languages.language.Language` or
:obj:`None` if no translation exists
"""
return self.get_prefetched_translations_by_language_slug(
attr="prefetched_public_or_draft_translations",
status__in=[status.DRAFT, status.PUBLIC],
)
def get_public_or_draft_translation(
self, language_slug: str
) -> AbstractContentTranslation | None:
"""
This function retrieves the newest public or draft translation of a content object.
:param language_slug: The slug of the requested :class:`~integreat_cms.cms.models.languages.language.Language`
:return: The public translation of a content object
"""
return self.prefetched_public_or_draft_translations_by_language_slug.get(
language_slug
)
@cached_property
def prefetched_major_public_translations_by_language_slug(
self,
) -> dict[str, AbstractContentTranslation]:
"""
This method returns a mapping from language slugs to their major public translations of this object
:return: The object translation in the requested :class:`~integreat_cms.cms.models.languages.language.Language` or
:obj:`None` if no translation exists
"""
return self.get_prefetched_translations_by_language_slug(
attr="prefetched_major_public_translations",
status=status.PUBLIC,
minor_edit=False,
)
def get_major_public_translation(
self, language_slug: str
) -> AbstractContentTranslation | None:
"""
This function retrieves the newest major public translation of a content object.
:param language_slug: The slug of the requested :class:`~integreat_cms.cms.models.languages.language.Language`
:return: The public translation of a content object
"""
return self.prefetched_major_public_translations_by_language_slug.get(
language_slug
)
@cached_property
def prefetched_major_translations_by_language_slug(
self,
) -> dict[str, AbstractContentTranslation]:
"""
This method returns a mapping from language slugs to their major translations of this object
:return: The object translation in the requested :class:`~integreat_cms.cms.models.languages.language.Language` or
:obj:`None` if no translation exists
"""
return self.get_prefetched_translations_by_language_slug(
attr="prefetched_major_translations",
minor_edit=False,
)
def get_major_translation(
self, language_slug: str
) -> AbstractContentTranslation | None:
"""
This function retrieves the newest major translation of a content object.
:param language_slug: The slug of the requested :class:`~integreat_cms.cms.models.languages.language.Language`
:return: The public translation of a content object
"""
return self.prefetched_major_translations_by_language_slug.get(language_slug)
def invalidate_cached_translations(self) -> None:
"""
Delete all cached translations and query them from the
database again when they are accessed next time.
This is helpful when new translations have been created
and the content model should be reused.
"""
for prefetched_attr in [
"backend_translation",
"best_translation",
"default_translation",
"default_public_translation",
"prefetched_translations_by_language_slug",
"prefetched_major_public_translations_by_language_slug",
"prefetched_major_translations_by_language_slug",
"prefetched_public_or_draft_translations_by_language_slug",
"prefetched_public_translations_by_language_slug",
"translation_states",
]:
try:
delattr(self, prefetched_attr)
except AttributeError:
pass
@cached_property
def backend_translation(self) -> Any:
"""
This function returns the translation of this content object in the current backend language.
:return: The backend translation of a content object
"""
return self.get_translation(get_language())
@cached_property
def default_translation(self) -> AbstractContentTranslation | None:
"""
This function returns the translation of this content object in the region's default language.
Since a content object can only be created by creating a translation in the default language, this is guaranteed
to return a object translation (Exception: When the default language tree node is changed to another language
after the page has been created, the default translation might not exist).
:return: The default translation of a content object
"""
return self.get_translation(self.region.default_language.slug)
@cached_property
def default_public_translation(self) -> AbstractContentTranslation | None:
"""
This function returns the public translation of this content object in the region's default language.
:return: The default translation of a content object
"""
return self.get_public_translation(self.region.default_language.slug)
@cached_property
def best_translation(
self,
) -> AbstractContentTranslation:
"""
This function returns the translation of this content object in the current backend language and if it doesn't
exist, it provides a fallback to the translation in the region's default language.
:return: The "best" translation of a content object for displaying in the backend
"""
return (
self.backend_translation
or self.default_translation
or self.translations.first()
)
def get_translation_state(self, language_slug: str) -> str:
"""
This function returns the current state of a translation in the given language.
:param language_slug: The slug of the desired :class:`~integreat_cms.cms.models.languages.language.Language`
:return: A string describing the state of the translation, one of :data:`~integreat_cms.cms.constants.translation_status.CHOICES`
"""
if translation := self.get_translation(language_slug):
return translation.translation_state
if self.fallback_translations_enabled and self.get_translation(
self.region.default_language.slug
):
return translation_status.FALLBACK
return translation_status.MISSING
@cached_property
def translation_states(self) -> dict[str, tuple[Language, str]]:
"""
This property calculates all translations states of the object
:return: A dictionary containing each language as key and the given translation state as value
"""
return {
node.slug: (node.language, self.get_translation_state(node.slug))
for node in self.region.language_tree
if node.active
}
@property
def edit_lock_key(self) -> tuple[str | int | None, str]:
"""
This property returns the key that is used to lock this specific content object
:return: A tuple of the id of this object and the classname
"""
return (self.id, type(self).__name__)
def get_locking_user(self) -> Any | None:
"""
This method returns the user that is currently locking this content object.
:return: The user
"""
return get_locking_user(*self.edit_lock_key)
@cached_property
def backend_edit_link(self) -> str:
"""
This function returns the absolute url to the edit form of this region
:return: The url
"""
return self.best_translation.backend_edit_link
def __str__(self) -> str:
"""
This overwrites the default Django :meth:`~django.db.models.Model.__str__` method which would return ``AbstractContentModel object (id)``.
It is used in the Django admin backend and as label for ModelChoiceFields.
:return: A readable string representation of the content object
"""
return self.best_translation.title
def get_repr(self) -> str:
"""
This overwrites the default Django ``__repr__()`` method which would return ``<AbstractContentModel: AbstractContentModel object (id)>``.
It is used for logging.
:return: The canonical string representation of the content object
"""
class_name = type(self).__name__
translation_slug = f", slug: {self.best_translation.slug}" if self.id else ""
return f"<{class_name} (id: {self.id}, region: {self.region.slug}{translation_slug})>"
class Meta:
#: This model is an abstract base class
abstract = True