def initial_data(apps, schema_editor): ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') WebPage = apps.get_model('website.WebPage') # Create page content type webpage_content_type, created = ContentType.objects.get_or_create( model='webpage', app_label='website', ) # Delete the default home page generated by wagtail, # and replace it with a more useful page type. curr_homepage = Page.objects.filter(slug='home').delete() homepage = WebPage.objects.create( title="Home", slug='home', custom_template='coderedcms/pages/home_page.html', content_type=webpage_content_type, path='00010001', depth=2, numchild=0, url_path='/home/', locale_id=Locale.get_default().id, ) # Create a new default site Site.objects.create(hostname='localhost', site_name='Funny Communication', root_page_id=homepage.id, is_default_site=True)
def get(self, request, *args, **kwargs): self.locale = None enable_locale_filter = getattr(settings, "WAGTAIL_I18N_ENABLED", False) if enable_locale_filter: if request.GET.get("locale"): self.locale = get_object_or_404( Locale, language_code=request.GET["locale"]) else: self.locale = Locale.get_default() return super().get(request, *args, **kwargs)
def get_for_object(cls, object): try: return cls.objects.get(object=object) except cls.DoesNotExist: # Raises exception if doesn't exist (let it crash!) instance = object.get_instance(Locale.get_default()) return cls.objects.create( object=object, # TODO: How to deal with duplicate paths? path=cls.get_path(instance), )
def create(request, app_label, model_name): model = get_snippet_model_from_url_params(app_label, model_name) permission = get_permission_name('add', model) if not request.user.has_perm(permission): raise PermissionDenied for fn in hooks.get_hooks('before_create_snippet'): result = fn(request, model) if hasattr(result, 'status_code'): return result instance = model() # Set locale of the new instance if issubclass(model, TranslatableMixin): selected_locale = request.GET.get('locale') if selected_locale: instance.locale = get_object_or_404(Locale, language_code=selected_locale) else: instance.locale = Locale.get_default() # Make edit handler edit_handler = get_snippet_edit_handler(model) edit_handler = edit_handler.bind_to(request=request) form_class = edit_handler.get_form_class() if request.method == 'POST': form = form_class(request.POST, request.FILES, instance=instance) if form.is_valid(): form.save() messages.success( request, _("%(snippet_type)s '%(instance)s' created.") % { 'snippet_type': capfirst(model._meta.verbose_name), 'instance': instance }, buttons=[ messages.button( reverse('wagtailsnippets:edit', args=(app_label, model_name, quote(instance.pk))), _('Edit')) ]) for fn in hooks.get_hooks('after_create_snippet'): result = fn(request, instance) if hasattr(result, 'status_code'): return result urlquery = '' if isinstance(instance, TranslatableMixin ) and instance.locale is not Locale.get_default(): urlquery = '?locale=' + instance.locale.language_code return redirect( reverse('wagtailsnippets:list', args=[app_label, model_name]) + urlquery) else: messages.validation_error( request, _("The snippet could not be created due to errors."), form) else: form = form_class(instance=instance) edit_handler = edit_handler.bind_to(instance=instance, form=form) context = { 'model_opts': model._meta, 'edit_handler': edit_handler, 'form': form, 'action_menu': SnippetActionMenu(request, view='create', model=model), 'locale': None, 'translations': [], } if getattr(settings, 'WAGTAIL_I18N_ENABLED', False) and issubclass( model, TranslatableMixin): context.update({ 'locale': instance.locale, 'translations': [{ 'locale': locale, 'url': reverse('wagtailsnippets:add', args=[app_label, model_name]) + '?locale=' + locale.language_code } for locale in Locale.objects.all().exclude(id=instance.locale.id) ], }) return TemplateResponse(request, 'wagtailsnippets/snippets/create.html', context)
def create(request, app_label, model_name): model = get_snippet_model_from_url_params(app_label, model_name) permission = get_permission_name("add", model) if not request.user.has_perm(permission): raise PermissionDenied for fn in hooks.get_hooks("before_create_snippet"): result = fn(request, model) if hasattr(result, "status_code"): return result instance = model() # Set locale of the new instance if issubclass(model, TranslatableMixin): selected_locale = request.GET.get("locale") if selected_locale: instance.locale = get_object_or_404(Locale, language_code=selected_locale) else: instance.locale = Locale.get_default() # Make edit handler edit_handler = get_snippet_edit_handler(model) edit_handler = edit_handler.bind_to(request=request) form_class = edit_handler.get_form_class() if request.method == "POST": form = form_class(request.POST, request.FILES, instance=instance) if form.is_valid(): with transaction.atomic(): form.save() log(instance=instance, action="wagtail.create") messages.success( request, _("%(snippet_type)s '%(instance)s' created.") % { "snippet_type": capfirst(model._meta.verbose_name), "instance": instance, }, buttons=[ messages.button( reverse( "wagtailsnippets:edit", args=(app_label, model_name, quote(instance.pk)), ), _("Edit"), ) ], ) for fn in hooks.get_hooks("after_create_snippet"): result = fn(request, instance) if hasattr(result, "status_code"): return result urlquery = "" if (isinstance(instance, TranslatableMixin) and instance.locale is not Locale.get_default()): urlquery = "?locale=" + instance.locale.language_code return redirect( reverse("wagtailsnippets:list", args=[app_label, model_name]) + urlquery) else: messages.validation_error( request, _("The snippet could not be created due to errors."), form) else: form = form_class(instance=instance) edit_handler = edit_handler.bind_to(instance=instance, form=form) context = { "model_opts": model._meta, "edit_handler": edit_handler, "form": form, "action_menu": SnippetActionMenu(request, view="create", model=model), "locale": None, "translations": [], } if getattr(settings, "WAGTAIL_I18N_ENABLED", False) and issubclass( model, TranslatableMixin): context.update({ "locale": instance.locale, "translations": [{ "locale": locale, "url": reverse("wagtailsnippets:add", args=[app_label, model_name]) + "?locale=" + locale.language_code, } for locale in Locale.objects.all().exclude(id=instance.locale.id) ], }) return TemplateResponse(request, "wagtailsnippets/snippets/create.html", context)
def setUp(self): self.src_locale = Locale.get_default() self.locale = Locale.objects.create(language_code="fr")
def test_default_doesnt_have_to_be_english(self): locale = Locale.get_default() self.assertEqual(locale.language_code, "fr")
def test_default(self): locale = Locale.get_default() self.assertEqual(locale.language_code, "en")
def _push(repo, logger): reader = repo.reader() writer = repo.writer() # Note: Reader is None on initial commit if reader: writer.copy_unmanaged_files(reader) def update_po(filename, new_po): if reader is not None: try: current_po_string = reader.read_file(filename).decode("utf-8") except KeyError: pass else: current_po = polib.pofile(current_po_string, wrapwidth=200) # Take metadata from existing PO file translation_id = new_po.metadata.get( "X-WagtailLocalize-TranslationID") new_po.metadata = current_po.metadata if translation_id: new_po.metadata[ "X-WagtailLocalize-TranslationID"] = translation_id writer.write_file(filename, str(new_po)) source_locale = Locale.get_default() target_locales = Locale.objects.exclude(id=source_locale.id) paths = defaultdict(list) for translation in (Translation.objects.filter( source__locale=source_locale, target_locale__in=target_locales, enabled=True).select_related( "source", "target_locale").order_by("target_locale__language_code")): resource = Resource.get_for_object(translation.source.object) source_po = translation.source.export_po() source_po_filename = po_filename_for_object(resource) update_po(str(source_po_filename), source_po) locale_po = translation.export_po() update_po( str( po_filename_for_object( resource, target_locale=translation.target_locale)), locale_po, ) paths[(source_po_filename, locale_po_filename_template_for_object(resource))].append( translation.target_locale) paths = [(source_filename, locale_filename, locales) for (source_filename, locale_filename), locales in paths.items()] writer.write_config( [locale.language_code for locale in target_locales], paths, # TODO as_rfc5646_language_tag ) if writer.has_changes(): previous_commit = repo.get_head_commit_id() # Create a new log for this push log = SyncLog.objects.create(action=SyncLog.ACTION_PUSH, commit_id="") logger.info("Push: Committing changes") log.commit_id = writer.commit("Updates to source content") log.save(update_fields=["commit_id"]) successful_push = repo.push() if not successful_push: raise SyncPushError(f"Failed to push reference {log.commit_id}") # Add any resources that have changed to the log # This ignores any deletions since we don't care about those for _filename, _old_content, new_content in repo.get_changed_files( previous_commit, log.commit_id): # Note: get_changed_files only picks up changes in the locales/ folder so we can assume they're all PO # files and they have a Translation ID # (anything else that gets in there won't be written into the new commit so, effectively, they get deleted) po = polib.pofile(new_content.decode("utf-8")) translation = Translation.objects.get( uuid=po.metadata["X-WagtailLocalize-TranslationID"]) log.add_translation(translation) else: logger.info( "Push: Not committing anything as recent changes haven't affected any translatable content" )