-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathedit_translation.py
More file actions
1532 lines (1322 loc) · 56.3 KB
/
Copy pathedit_translation.py
File metadata and controls
1532 lines (1322 loc) · 56.3 KB
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 contextlib
import json
import os
import tempfile
from collections import defaultdict
import polib
from django.conf import settings
from django.contrib.admin.utils import quote
from django.contrib.auth import get_user_model
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models, transaction
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.utils.text import capfirst, slugify
from django.utils.translation import gettext as _
from django.views.decorators.http import require_POST
from modelcluster.fields import ParentalKey
from rest_framework import serializers, status
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import (
api_view,
authentication_classes,
permission_classes,
)
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from wagtail import blocks
from wagtail.admin import messages
from wagtail.admin.panels import FieldPanel, InlinePanel, ObjectList, TabbedInterface
from wagtail.admin.panels import PanelGroup as BaseCompositeEditHandler
from wagtail.admin.panels import get_edit_handler as get_snippet_edit_handler
from wagtail.admin.templatetags.wagtailadmin_tags import avatar_url
from wagtail.admin.ui.components import MediaContainer
from wagtail.admin.views.pages.utils import get_valid_next_url_from_request
from wagtail.coreutils import cautious_slugify
from wagtail.documents.blocks import DocumentChooserBlock
from wagtail.documents.models import AbstractDocument
from wagtail.fields import StreamField
from wagtail.images.blocks import ImageChooserBlock
from wagtail.images.models import AbstractImage
from wagtail.models import DraftStateMixin, Page, TranslatableMixin
from wagtail.snippets.blocks import SnippetChooserBlock
from wagtail.snippets.models import get_snippet_models
from wagtail.snippets.permissions import get_permission_name, user_can_edit_snippet_type
from wagtail.utils.decorators import xframe_options_sameorigin_override
from wagtail_localize.compat import DATE_FORMAT
from wagtail_localize.machine_translators import get_machine_translator
from wagtail_localize.models import (
OverridableSegment,
SegmentOverride,
StringSegment,
StringTranslation,
Translation,
TranslationSource,
)
from wagtail_localize.segments import StringSegmentValue
class UserSerializer(serializers.ModelSerializer):
full_name = serializers.ReadOnlyField(source="get_full_name")
avatar_url = serializers.SerializerMethodField("get_avatar_url")
def get_avatar_url(self, user):
return avatar_url(user, size=25)
class Meta:
model = get_user_model()
fields = ["full_name", "avatar_url"]
class StringTranslationSerializer(serializers.ModelSerializer):
string_id = serializers.ReadOnlyField(source="translation_of_id")
segment_id = serializers.SerializerMethodField("get_segment_id")
error = serializers.ReadOnlyField(source="get_error")
comment = serializers.ReadOnlyField(source="get_comment")
last_translated_by = UserSerializer()
def get_segment_id(self, translation):
if "translation_source" in self.context:
translation_source = self.context["translation_source"]
return (
translation_source.stringsegment_set.filter(
string_id=translation.translation_of_id,
context_id=translation.context_id,
)
.values_list("id", flat=True)
.first()
)
class Meta:
model = StringTranslation
fields = [
"string_id",
"segment_id",
"data",
"error",
"comment",
"last_translated_by",
]
class SegmentOverrideSerializer(serializers.ModelSerializer):
segment_id = serializers.SerializerMethodField("get_segment_id")
error = serializers.ReadOnlyField(source="get_error")
def get_segment_id(self, override):
if "translation_source" in self.context:
translation_source = self.context["translation_source"]
try:
return (
translation_source.overridablesegment_set.only("id")
.get(
context_id=override.context_id,
)
.id
)
except OverridableSegment.DoesNotExist:
return
class Meta:
model = SegmentOverride
fields = ["segment_id", "data", "error"]
class TabHelper:
def __init__(self, instance):
self.instance = instance
@cached_property
def edit_handler(self):
if isinstance(self.instance, Page):
return self.instance.get_edit_handler()
else:
return get_snippet_edit_handler(self.instance.__class__)
@cached_property
def tabs(self):
tabs = []
if isinstance(self.edit_handler, TabbedInterface):
for tab in self.edit_handler.children:
# On Pages, the TabbedInterface children are instances of ObjectList
# which contain the fields
# On Snippets, the fields can be added directly into the TabbedInterface
# In this case, we do not want to add any tabs and instead just fall back
# to the default "Content" tab added below.
if isinstance(tab, ObjectList):
tabs.append(tab.heading)
# Add a default "Content" tab if this object doesn't have any tabs
if not tabs:
tabs = [_("Content")]
return tabs
@property
def tabs_with_slugs(self):
return [
{
"label": label,
"slug": cautious_slugify(label),
}
for label in self.tabs
]
@cached_property
def field_tab_mapping(self):
# ObjectList used to inherit from TabbedInterface pre 3.0. Now they both inherit from PanelGroup
# Ideally we would check on PanelGroup, however FieldRowPanel and MultiRowPanel do so too, but we're
# only interested in "tabbing"
is_tabbed = isinstance(self.edit_handler, TabbedInterface | ObjectList)
if is_tabbed:
field_tabs = {}
for tab in self.edit_handler.children:
form_options = tab.get_form_options()
required_fields = form_options.get("fields", [])
required_formsets = form_options.get("formsets", {}).keys()
for tab_field in required_fields:
field_tabs[tab_field] = tab.heading
for tab_formset in required_formsets:
field_tabs[tab_formset] = tab.heading
return field_tabs
else:
return {}
def get_field_tab(self, field_name):
if field_name in self.field_tab_mapping:
return self.field_tab_mapping[field_name]
else:
raise KeyError(f"Cannot find tab for field '{field_name}''")
@cached_property
def field_ordering_mapping(self):
# ObjectList used to inherit from TabbedInterface pre 3.0. Now they both inherit from PanelGroup
# Ideally we would check on PanelGroup, however FieldRowPanel and MultiRowPanel do so too, but we're
# only interested in "tabbing"
is_tabbed = isinstance(self.edit_handler, TabbedInterface | ObjectList)
if is_tabbed:
field_orderings = {}
order = 0
for tab in self.edit_handler.children:
form_options = tab.get_form_options()
required_fields = form_options.get("fields", [])
required_formsets = form_options.get("formsets", {})
for tab_field in required_fields:
# TODO(someday): Orderings of fields within inline panels.
# (currently, they will all be assigned the same order value,
# so they will end up being order by how they are defined on
# the model instead of the panel definition.
# But this should be OK for most people)
field_orderings[tab_field] = order
order += 1
for tab_formset in required_formsets:
field_orderings[tab_formset] = order
order += 1
return field_orderings
else:
return {}
def get_field_order(self, field_name):
if field_name in self.field_ordering_mapping:
return self.field_ordering_mapping[field_name]
else:
raise KeyError(f"Cannot find ordering for field '{field_name}''")
@cached_property
def field_edit_handler_mapping(self):
# TODO (someday): Extract mappings out of inline panels
field_edit_handlers = {}
def walk(edit_handler):
if isinstance(edit_handler, BaseCompositeEditHandler):
for child in edit_handler.children:
walk(child)
elif isinstance(edit_handler, FieldPanel):
field_edit_handlers[edit_handler.field_name] = edit_handler
elif (
isinstance(edit_handler, InlinePanel) and edit_handler.model is not None
):
for panel in edit_handler.child_edit_handler.children:
walk(panel)
walk(self.edit_handler)
return field_edit_handlers
def get_field_edit_handler(self, field_name):
if field_name in self.field_edit_handler_mapping:
return self.field_edit_handler_mapping[field_name]
class FieldHasNoEditPanelError(KeyError):
pass
def get_segment_location_info(
source_instance, tab_helper, content_path, field_path, widget=False
):
content_path_components = content_path.split(".")
field_path_components = field_path.split(".")
field = source_instance._meta.get_field(field_path_components[0])
# Work out which tab the segment is on from edit handler
try:
tab = cautious_slugify(tab_helper.get_field_tab(field.name))
except KeyError as err:
raise FieldHasNoEditPanelError from err
order = tab_helper.get_field_order(field.name)
def widget_from_field(field):
if isinstance(field, models.ForeignKey):
if issubclass(field.related_model, Page):
edit_handler = tab_helper.get_field_edit_handler(field.name)
# @see https://github.com/wagtail/wagtail/pull/7684
# the target_models is set in the ModelFieldRegistry for ForeignKeys
widget_overrides = edit_handler.get_form_options().get("widgets", {})
# Check for explicit `page_types` kwarg in PageChooserPanel
if field.name in widget_overrides and hasattr(
widget_overrides[field.name], "target_models"
):
allowed_page_types = [
f"{model._meta.app_label}.{model._meta.model_name}"
for model in widget_overrides[field.name].target_models
]
else:
from wagtail.admin.forms.models import registry
allowed_page_types = [
f"{model._meta.app_label}.{model._meta.model_name}"
for model in registry.foreign_key_lookup(field)[
"widget"
].target_models
]
return {
"type": "page_chooser",
"allowed_page_types": allowed_page_types,
}
elif issubclass(field.related_model, AbstractDocument):
return {"type": "document_chooser"}
elif issubclass(field.related_model, AbstractImage):
return {"type": "image_chooser"}
elif issubclass(field.related_model, tuple(get_snippet_models())):
chooser_url = reverse(
f"wagtailsnippetchoosers_{field.related_model._meta.app_label}_{field.related_model._meta.model_name}:choose"
)
return {
"type": "snippet_chooser",
"snippet_model": {
"app_label": field.related_model._meta.app_label,
"model_name": field.related_model._meta.model_name,
"verbose_name": field.related_model._meta.verbose_name,
"verbose_name_plural": field.related_model._meta.verbose_name_plural,
},
"chooser_url": chooser_url,
}
elif isinstance(
field,
models.CharField | models.TextField | models.EmailField | models.URLField,
):
return {
"type": "text",
}
return {"type": "unknown"}
def widget_from_block(block, content_components=None):
if isinstance(block, blocks.PageChooserBlock):
return {
"type": "page_chooser",
"allowed_page_types": [
f"{model._meta.app_label}.{model._meta.model_name}"
# Note: Unlike PageChooserPanel, the block doesn't automatically fall back to [Page]
for model in block.target_models or [Page]
],
}
elif isinstance(block, DocumentChooserBlock):
return {"type": "document_chooser"}
elif isinstance(block, ImageChooserBlock):
return {"type": "image_chooser"}
elif isinstance(block, SnippetChooserBlock):
chooser_url = reverse(
f"wagtailsnippetchoosers_{block.target_model._meta.app_label}_{block.target_model._meta.model_name}:choose"
)
return {
"type": "snippet_chooser",
"snippet_model": {
"app_label": block.target_model._meta.app_label,
"model_name": block.target_model._meta.model_name,
"verbose_name": block.target_model._meta.verbose_name,
"verbose_name_plural": block.target_model._meta.verbose_name_plural,
},
"chooser_url": chooser_url,
}
elif isinstance(
block,
blocks.CharBlock
| blocks.TextBlock
| blocks.RichTextBlock
| blocks.EmailBlock
| blocks.URLBlock,
):
return {
"type": "text",
}
elif (
isinstance(block, blocks.StructBlock | blocks.StreamBlock)
and content_components
and isinstance(content_components, list)
):
block_field_name = content_components.pop(0)
return widget_from_block(
block.child_blocks.get(block_field_name), content_components
)
elif isinstance(block, blocks.ListBlock):
if content_components is not None:
return widget_from_block(block.child_block, content_components[1:])
return widget_from_block(block.child_block)
return {"type": "unknown"}
if isinstance(field, StreamField):
block_type_name = field_path_components[1]
block_type = field.stream_block.child_blocks[block_type_name]
if isinstance(block_type, blocks.StructBlock | blocks.StreamBlock):
block_field_name = field_path_components[2]
block_field = block_type.child_blocks[block_field_name].label
content_components = field_path_components[2:]
elif isinstance(block_type, blocks.ListBlock):
block_field = None
content_components = None
if isinstance(
block_type.child_block, blocks.StructBlock | blocks.StreamBlock
):
block_field_name = field_path_components[3]
block_field = block_type.child_block.child_blocks[
block_field_name
].label
content_components = field_path_components[2:]
else:
block_field = None
content_components = None
return {
"tab": tab,
"field": capfirst(block_type.label),
"order": order,
"blockId": content_path_components[1],
"fieldHelpText": "",
"subField": block_field,
"widget": widget_from_block(block_type, content_components)
if widget
else None,
}
elif (
isinstance(field, models.ManyToOneRel)
and isinstance(field.remote_field, ParentalKey)
and issubclass(field.related_model, TranslatableMixin)
):
child_field = field.related_model._meta.get_field(field_path_components[1])
return {
"tab": tab,
"field": capfirst(field.related_model._meta.verbose_name),
"order": order,
"blockId": content_path_components[1],
"fieldHelpText": getattr(child_field, "help_text", ""),
"subField": capfirst(child_field.verbose_name)
if hasattr(child_field, "verbose_name")
else None,
"widget": widget_from_field(child_field) if widget else None,
}
else:
return {
"tab": tab,
"field": capfirst(field.verbose_name),
"order": order,
"blockId": None,
"fieldHelpText": getattr(field, "help_text", ""),
"subField": None,
"widget": widget_from_field(field) if widget else None,
}
def edit_translation(request, translation: Translation, instance):
if isinstance(instance, Page):
# Page
# Note: Edit permission is already checked by the edit page view
page_perms = instance.permissions_for_user(request.user)
is_page = True
is_live = instance.live
is_locked = instance.locked
if instance.live_revision:
last_published_at = instance.live_revision.created_at
last_published_by = instance.live_revision.user
else:
last_published_at = instance.last_published_at
last_published_by = None
live_url = instance.full_url if instance.live else None
can_publish = page_perms.can_publish()
can_unpublish = page_perms.can_unpublish()
can_lock = page_perms.can_lock()
can_unlock = page_perms.can_unlock()
can_delete = page_perms.can_delete()
elif isinstance(instance, DraftStateMixin):
# Draftable Snippet
# Note: Edit permission is already checked by the edit snippet view
page_perms = None
is_page = False
is_live = bool(instance.live_revision)
is_locked = False
last_published_at = instance.live_revision.created_at if is_live else None
last_published_by = instance.live_revision.user if is_live else None
live_url = None
can_publish = (
request.user.has_perm(get_permission_name("publish", instance.__class__))
or request.user.is_superuser
)
can_unpublish = False # Snippets can't be unpublished
can_lock = False
can_unlock = False
can_delete = request.user.has_perm(
get_permission_name("delete", instance.__class__)
)
else:
# Snippet
# Note: Edit permission is already checked by the edit snippet view
page_perms = None
is_page = False
is_live = True
is_locked = False
last_published_at = None
last_published_by = None
live_url = None
can_publish = True
can_unpublish = False
can_lock = False
can_unlock = False
can_delete = request.user.has_perm(
get_permission_name("delete", instance.__class__)
)
source_instance = translation.source.get_source_instance()
if request.method == "POST":
if request.POST.get("action") == "publish":
if isinstance(instance, DraftStateMixin):
if isinstance(instance, Page):
if not page_perms.can_publish():
raise PermissionDenied
elif (
not request.user.has_perm(
get_permission_name("publish", instance.__class__)
)
and not request.user.is_superuser
):
raise PermissionDenied
try:
translation.save_target(user=request.user, publish=True)
except ValidationError:
messages.error(
request,
_(
"New validation errors were found when publishing '{object}' in {locale}. Please fix them or click publish again to ignore these translations for now."
).format(
object=str(instance),
locale=translation.target_locale.get_display_name(),
),
)
else:
# Refresh instance to title in success message is up to date
instance.refresh_from_db()
string_segments = translation.source.stringsegment_set.all().order_by(
"order"
)
string_translations = string_segments.get_translations(
translation.target_locale
)
# Using annotate_translation as this ignores errors by default (so both errors and missing segments treated the same)
if (
string_segments.annotate_translation(translation.target_locale)
.filter(translation__isnull=True)
.exists()
):
# One or more strings had an error
messages.warning(
request,
_(
"Published '{object}' in {locale} with missing translations - see below."
).format(
object=str(instance),
locale=translation.target_locale.get_display_name(),
),
)
else:
messages.success(
request,
_("Published '{object}' in {locale}.").format(
object=str(instance),
locale=translation.target_locale.get_display_name(),
),
)
return redirect(request.path)
string_segments_qs = (
translation.source.stringsegment_set.select_related("context", "string")
.all()
.order_by("order")
)
string_translations = string_segments_qs.get_translations(
translation.target_locale
).select_related("last_translated_by", "translation_of")
string_segments = list(string_segments_qs)
segment_context_ids = [segment.context_id for segment in string_segments]
previous_translations_by_context = defaultdict(list)
if segment_context_ids:
historical_translations = (
StringTranslation.objects.filter(
locale=translation.target_locale,
context_id__in=segment_context_ids,
)
.select_related("translation_of", "last_translated_by")
.order_by("context_id", "-updated_at")
)
for historical_translation in historical_translations:
previous_translations_by_context[historical_translation.context_id].append(
historical_translation
)
overridable_segments = translation.source.overridablesegment_set.all().order_by(
"order"
)
segment_overrides = overridable_segments.get_overrides(translation.target_locale)
related_object_segments = (
translation.source.relatedobjectsegment_set.all().order_by("order")
)
tab_helper = TabHelper(source_instance)
breadcrumb = []
title_segment_id = None
if isinstance(instance, Page):
# find the closest common ancestor of the pages that this user has direct explore permission
# (i.e. add/edit/publish/lock) over; this will be the root of the breadcrumb
from wagtail.permission_policies.pages import PagePermissionPolicy
cca = PagePermissionPolicy().explorable_root_instance(request.user)
if cca:
breadcrumb = [
{
"id": page.id,
"isRoot": page.is_root(),
"title": page.title,
"exploreUrl": reverse("wagtailadmin_explore_root")
if page.is_root()
else reverse("wagtailadmin_explore", args=[page.id]),
}
for page in instance.get_ancestors(inclusive=False).descendant_of(
cca, inclusive=True
)
]
# Set to the ID of a string segment that represents the title.
# If this segment has a translation, the title will be replaced with that translation.
title_segment_id = next(
(
segment.id
for segment in string_segments
if segment.context.path == "title"
),
None,
)
machine_translator = None
translator = get_machine_translator()
if translator and translator.can_translate(
translation.source.locale, translation.target_locale
):
machine_translator = {
"name": translator.display_name,
"url": reverse("wagtail_localize:machine_translate", args=[translation.id]),
}
segments = []
for segment in string_segments:
try:
location_info = get_segment_location_info(
source_instance,
tab_helper,
segment.context.path,
segment.context.get_field_path(source_instance),
)
except FieldHasNoEditPanelError:
continue
previous_translation_data = None
for previous_translation in previous_translations_by_context.get(
segment.context_id, []
):
if previous_translation.translation_of_id == segment.string_id:
continue
previous_translation_data = {
"value": previous_translation.data,
"source": previous_translation.translation_of.data,
"comment": previous_translation.get_comment(),
"translatedBy": UserSerializer(
previous_translation.last_translated_by
).data
if previous_translation.last_translated_by
else None,
"updatedAt": (
previous_translation.updated_at.isoformat()
if previous_translation.updated_at
else None
),
}
break
segments.append(
{
"type": "string",
"id": segment.id,
"contentPath": segment.context.path,
"source": segment.string.data,
"location": location_info,
"editUrl": reverse(
"wagtail_localize:edit_string_translation",
kwargs={
"translation_id": translation.id,
"string_segment_id": segment.id,
},
),
"order": segment.order,
"previousTranslation": previous_translation_data,
}
)
for segment in overridable_segments:
try:
location_info = get_segment_location_info(
source_instance,
tab_helper,
segment.context.path,
segment.context.get_field_path(source_instance),
widget=True,
)
except FieldHasNoEditPanelError:
continue
segments.append(
{
"type": "synchronised_value",
"id": segment.id,
"contentPath": segment.context.path,
"location": location_info,
"value": segment.data,
"editUrl": reverse(
"wagtail_localize:edit_override",
kwargs={
"translation_id": translation.id,
"overridable_segment_id": segment.id,
},
),
"order": segment.order,
}
)
def get_edit_url(instance):
if isinstance(instance, Page):
return reverse("wagtailadmin_pages:edit", args=[instance.id])
elif instance._meta.model in get_snippet_models():
return reverse(
f"wagtailsnippets_{instance._meta.app_label}_{instance._meta.model_name}:edit",
args=[quote(instance.pk)],
)
elif "wagtail_localize.modeladmin" in settings.INSTALLED_APPS:
return reverse(
f"{instance._meta.app_label}_{instance._meta.model_name}_modeladmin_edit",
args=[quote(instance.pk)],
)
def get_delete_url(instance):
if isinstance(instance, Page):
return reverse("wagtailadmin_pages:delete", args=[instance.id])
elif instance._meta.model in get_snippet_models():
return reverse(
f"wagtailsnippets_{instance._meta.app_label}_{instance._meta.model_name}:delete",
args=[quote(instance.pk)],
)
elif "wagtail_localize.modeladmin" in settings.INSTALLED_APPS:
return reverse(
f"{instance._meta.app_label}_{instance._meta.model_name}_modeladmin_delete",
args=[quote(instance.pk)],
)
def get_submit_translation_url(instance):
if isinstance(instance, Page):
return reverse(
"wagtail_localize:submit_page_translation", args=[instance.id]
)
elif instance._meta.model in get_snippet_models():
return reverse(
"wagtail_localize:submit_snippet_translation",
args=[
instance._meta.app_label,
instance._meta.model_name,
quote(instance.id),
],
)
elif "wagtail_localize.modeladmin" in settings.INSTALLED_APPS:
return reverse(
"wagtail_localize_modeladmin:submit_translation",
args=[
instance._meta.app_label,
instance._meta.model_name,
quote(instance.id),
],
)
def get_source_object_info(segment):
instance = segment.get_source_instance()
if isinstance(instance, Page):
return {
"title": str(instance),
"isLive": instance.live,
"liveUrl": instance.full_url,
"editUrl": get_edit_url(instance),
"createTranslationRequestUrl": get_submit_translation_url(instance),
}
else:
return {
"title": str(instance),
"isLive": instance.live
if isinstance(instance, DraftStateMixin)
else True,
"editUrl": get_edit_url(instance),
"createTranslationRequestUrl": get_submit_translation_url(instance),
}
def get_dest_object_info(segment):
instance = segment.object.get_instance_or_none(translation.target_locale)
if not instance:
return
if isinstance(instance, Page):
return {
"title": str(instance),
"isLive": instance.live,
"liveUrl": instance.full_url,
"editUrl": get_edit_url(instance),
}
else:
return {
"title": str(instance),
"isLive": instance.live
if isinstance(instance, DraftStateMixin)
else True,
"editUrl": get_edit_url(instance),
}
def get_translation_progress(segment, locale):
try:
translation = Translation.objects.get(
source__object_id=segment.object_id, target_locale=locale, enabled=True
)
except Translation.DoesNotExist:
return None
total_segments, translated_segments = translation.get_progress()
return {
"totalSegments": total_segments,
"translatedSegments": translated_segments,
}
for segment in related_object_segments:
try:
location_info = get_segment_location_info(
source_instance,
tab_helper,
segment.context.path,
segment.context.get_field_path(source_instance),
)
except FieldHasNoEditPanelError:
continue
segments.append(
{
"type": "related_object",
"id": segment.id,
"contentPath": segment.context.path,
"location": location_info,
"order": segment.order,
"source": get_source_object_info(segment),
"dest": get_dest_object_info(segment),
"translationProgress": get_translation_progress(
segment, translation.target_locale
),
}
)
# Order segments by how they appear in the content panels
# segment['location']['order'] is the content panel ordering
# segment['order'] is the model field ordering
# User's expect segments to follow the panel ordering as that's the ordering
# that is used in the page editor of the source page. However, segments that
# come from the same streamfield/inline panel are given the same value for
# panel ordering, so we need to order by model field ordering as well (all
# segments have a unique value for model field ordering)
segments.sort(key=lambda segment: (segment["location"]["order"], segment["order"]))
# Display a warning to the user if the schema of the source model has been updated since the source was last updated
if translation.source.schema_out_of_date():
messages.warning(
request,
_(
"The data model for '{model_name}' has been changed since the last translation sync. "
"If any new fields have been added recently, these may not be visible until the next translation sync."
).format(model_name=capfirst(source_instance._meta.verbose_name)),
)
if isinstance(instance, Page):
try:
# Check that there is a parent page.
add_convert_to_alias_url = (
Page.objects.filter(
translation_key=instance.translation_key,
locale_id=TranslationSource.objects.get(
object_id=instance.translation_key,
specific_content_type=instance.content_type_id,
translations__target_locale=instance.locale,
).locale_id,
)
.exclude(pk=instance.pk)
.exists()
)
except (TranslationSource.DoesNotExist, IndexError):
add_convert_to_alias_url = False
else:
add_convert_to_alias_url = False
translations = instance.get_translations().select_related("locale")
props_translations = [
{
"title": str(translated_instance),
"locale": {
"code": translated_instance.locale.language_code,
"displayName": translated_instance.locale.get_display_name(),
},
"editUrl": get_edit_url(translated_instance),
}
for translated_instance in translations
]
context = {
"translation": translation,
"instance": instance,
"is_page": is_page,
"page_perms": page_perms,
"model_opts": instance._meta,
"source_translation": [
_translation
for _translation in props_translations
if _translation["locale"]["code"] == translation.source.locale.language_code
][0],
"translations": [
(_translation["locale"]["displayName"], _translation["editUrl"])
for _translation in props_translations
if _translation["locale"]["code"] != translation.source.locale.language_code
],
"source_locale": translation.source.locale,
"target_locale": translation.target_locale,
# These props are passed directly to the TranslationEditor react component
"props": json.dumps(
{
"adminBaseUrl": reverse("wagtailadmin_home"),
"object": {
"title": str(instance),
"titleSegmentId": title_segment_id,
"isLive": is_live,
"isLocked": is_locked,
"lastPublishedDate": last_published_at.strftime(DATE_FORMAT)