Merge branch 'master' into master

This commit is contained in:
Diogo Marques 2019-10-23 12:22:29 +01:00 committed by GitHub
commit 8b945cec37
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 220 additions and 5 deletions

View file

@ -3,5 +3,6 @@ recursive-include docs *.rst conf.py Makefile make.bat
recursive-include wagtail_modeltranslation/static *
recursive-include wagtail_modeltranslation/management *
recursive-include wagtail_modeltranslation/templatetags *
recursive-include wagtail_modeltranslation/templates *
global-exclude *.pyc
global-exclude *.DS_Store

View file

@ -1,6 +1,6 @@
Metadata-Version: 1.0
Name: wagtail-modeltranslation
Version: 0.10.1
Version: 0.10.5
Summary: Translates Wagtail CMS models using a registration approach.
Home-page: https://github.com/infoportugal/wagtail-modeltranslation
Author: InfoPortugal S.A.

View file

@ -1,5 +1,5 @@
[bumpversion]
current_version = 0.10.2
current_version = 0.10.5
commit = True
tag = True

View file

@ -44,7 +44,8 @@ setup(
'wagtail_modeltranslation.migrate.management',
'wagtail_modeltranslation.migrate.management.commands'],
package_data={'wagtail_modeltranslation': ['static/wagtail_modeltranslation/css/*.css',
'static/wagtail_modeltranslation/js/*.js']},
'static/wagtail_modeltranslation/js/*.js',
'templates/*.html']},
install_requires=['wagtail>=1.12', 'django-modeltranslation>=0.13'],
classifiers=[
'Programming Language :: Python',

View file

@ -1,3 +1,3 @@
# coding: utf-8
__version__ = '0.10.2'
__version__ = '0.10.5'
default_app_config = 'wagtail_modeltranslation.apps.ModeltranslationConfig'

View file

@ -0,0 +1,107 @@
# coding: utf-8
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
try:
from wagtail.core.models import Page
from wagtail.admin import widgets
from wagtail.admin.forms.pages import CopyForm
except ImportError:
from wagtail.wagtailcore.models import Page
from wagtail.wagtailadmin import widgets
from wagtail.wagtailadmin.forms import CopyForm
class PatchedCopyForm(CopyForm):
def __init__(self, *args, **kwargs):
# CopyPage must be passed a 'page' kwarg indicating the page to be copied
self.page = kwargs.pop('page')
self.user = kwargs.pop('user', None)
can_publish = kwargs.pop('can_publish')
super(CopyForm, self).__init__(*args, **kwargs)
#self.fields['new_title'] = forms.CharField(initial=self.page.title, label=_("New title"))
for code, name in settings.LANGUAGES:
locale_title = "new_title_{}".format(code)
locale_label = "{} [{}]".format(_("New title"), code)
self.fields[locale_title] = forms.CharField(initial=self.page.title, label=locale_label)
#self.fields['new_slug'] = forms.SlugField(initial=self.page.slug, label=_("New slug"))
for code, name in settings.LANGUAGES:
locale_title = "new_slug_{}".format(code)
locale_label = "{} [{}]".format(_("New slug"), code)
self.fields[locale_title] = forms.SlugField(initial=self.page.slug, label=locale_label)
self.fields['new_parent_page'] = forms.ModelChoiceField(
initial=self.page.get_parent(),
queryset=Page.objects.all(),
widget=widgets.AdminPageChooser(can_choose_root=True, user_perms='copy_to'),
label=_("New parent page"),
help_text=_("This copy will be a child of this given parent page.")
)
pages_to_copy = self.page.get_descendants(inclusive=True)
subpage_count = pages_to_copy.count() - 1
if subpage_count > 0:
self.fields['copy_subpages'] = forms.BooleanField(
required=False, initial=True, label=_("Copy subpages"),
help_text=ungettext(
"This will copy %(count)s subpage.",
"This will copy %(count)s subpages.",
subpage_count) % {'count': subpage_count})
if can_publish:
pages_to_publish_count = pages_to_copy.live().count()
if pages_to_publish_count > 0:
# In the specific case that there are no subpages, customise the field label and help text
if subpage_count == 0:
label = _("Publish copied page")
help_text = _("This page is live. Would you like to publish its copy as well?")
else:
label = _("Publish copies")
help_text = ungettext(
"%(count)s of the pages being copied is live. Would you like to publish its copy?",
"%(count)s of the pages being copied are live. Would you like to publish their copies?",
pages_to_publish_count) % {'count': pages_to_publish_count}
self.fields['publish_copies'] = forms.BooleanField(
required=False, initial=True, label=label, help_text=help_text
)
def clean(self):
cleaned_data = super(CopyForm, self).clean()
# Make sure the slug isn't already in use
# slug = cleaned_data.get('new_slug')
# New parent page given in form or parent of source, if parent_page is empty
parent_page = cleaned_data.get('new_parent_page') or self.page.get_parent()
# check if user is allowed to create a page at given location.
if not parent_page.permissions_for_user(self.user).can_add_subpage():
raise ValidationError({
'new_parent_page': _("You do not have permission to copy to page \"%(page_title)s\"") % {'page_title': parent_page.get_admin_display_title()}
})
# Count the pages with the same slug within the context of our copy's parent page
for code, name in settings.LANGUAGES:
locale_slug = "new_slug_{}".format(code)
slug = cleaned_data.get(locale_slug)
param = 'slug_' + code
query = {param: slug}
if slug and parent_page.get_children().filter(**query).count():
raise ValidationError({
locale_slug: _("This slug is already in use within the context of its parent page \"%s\"" % parent_page)
})
# Don't allow recursive copies into self
if cleaned_data.get('copy_subpages') and (self.page == parent_page or parent_page.is_descendant_of(self.page)):
raise ValidationError({
'new_parent_page': _("You cannot copy a page into itself when copying subpages")
})
return cleaned_data

View file

@ -0,0 +1,31 @@
{% extends "wagtailadmin/base.html" %}
{% load i18n %}
{% block titletag %}{% blocktrans with title=page.get_admin_display_title %}Copy {{ title }}{% endblocktrans %}{% endblock %}
{% block content %}
{% trans "Copy" as copy_str %}
{% include "wagtailadmin/shared/header.html" with title=copy_str subtitle=page.get_admin_display_title icon="doc-empty-inverse" %}
<div class="nice-padding">
<form action="{% url 'wagtailadmin_pages:copy' page.id %}" method="POST" novalidate>
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}" />
<ul class="fields">
{% for field in form.visible_fields %}
{% include "wagtailadmin/shared/field_as_li.html" with field=field %}
{% endfor %}
{% if form.copy_subpages %}
{% include "wagtailadmin/shared/field_as_li.html" with field=form.copy_subpages %}
{% endif %}
</ul>
<input type="submit" value="{% trans 'Copy this page' %}" class="button">
</form>
</div>
{% endblock %}
{% block extra_js %}
{{ block.super }}
{% include "wagtailadmin/pages/_editor_js.html" %}
{% endblock %}

View file

@ -2,27 +2,35 @@
import json
from django.core.exceptions import PermissionDenied
from six import iteritems
from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse, QueryDict
from django.shortcuts import redirect, render
from django.templatetags.static import static
from django.utils.html import escape, format_html, format_html_join
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import csrf_exempt
from wagtail_modeltranslation import settings as wmt_settings
from modeltranslation import settings as mt_settings
from .patch_wagtailadmin_forms import PatchedCopyForm
try:
from wagtail.core import hooks
from wagtail.core.models import Page
from wagtail.core.rich_text.pages import PageLinkHandler
from wagtail.core import __version__ as WAGTAIL_VERSION
from wagtail.admin import messages
from wagtail.admin.views.pages import get_valid_next_url_from_request
except ImportError:
from wagtail.wagtailcore import hooks
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.rich_text import PageLinkHandler
from wagtail.wagtailcore import __version__ as WAGTAIL_VERSION
from wagtail.wagtailadmin import messages
from wagtail.wagtailadmin.views.pages import get_valid_next_url_from_request
@hooks.register('insert_editor_js')
@ -168,3 +176,70 @@ def register_localized_page_link_handler():
return "<a>"
return ('page', LocalizedPageLinkHandler)
@hooks.register('before_copy_page')
def before_copy_page(request, page):
parent_page = page.get_parent()
can_publish = parent_page.permissions_for_user(request.user).can_publish_subpage()
form = PatchedCopyForm(request.POST or None, user=request.user, page=page, can_publish=can_publish)
next_url = get_valid_next_url_from_request(request)
if request.method == 'POST':
# Prefill parent_page in case the form is invalid (as prepopulated value for the form field,
# because ModelChoiceField seems to not fall back to the user given value)
parent_page = Page.objects.get(id=request.POST['new_parent_page'])
if form.is_valid():
# Receive the parent page (this should never be empty)
if form.cleaned_data['new_parent_page']:
parent_page = form.cleaned_data['new_parent_page']
if not page.permissions_for_user(request.user).can_copy_to(parent_page,
form.cleaned_data.get('copy_subpages')):
raise PermissionDenied
# Re-check if the user has permission to publish subpages on the new parent
can_publish = parent_page.permissions_for_user(request.user).can_publish_subpage()
update_attrs = {}
for code, name in settings.LANGUAGES:
slug = "slug_{}".format(code)
title = "title_{}".format(code)
update_attrs[slug] = form.cleaned_data["new_{}".format(slug)]
update_attrs[title] = form.cleaned_data["new_{}".format(title)]
# Copy the page
new_page = page.copy(
recursive=form.cleaned_data.get('copy_subpages'),
to=parent_page,
update_attrs=update_attrs,
keep_live=(can_publish and form.cleaned_data.get('publish_copies')),
user=request.user,
)
# Give a success message back to the user
if form.cleaned_data.get('copy_subpages'):
messages.success(
request,
_("Page '{0}' and {1} subpages copied.").format(
page.get_admin_display_title(), new_page.get_descendants().count())
)
else:
messages.success(request, _("Page '{0}' copied.").format(page.get_admin_display_title()))
for fn in hooks.get_hooks('after_copy_page'):
result = fn(request, page, new_page)
if hasattr(result, 'status_code'):
return result
# Redirect to explore of parent page
if next_url:
return redirect(next_url)
return redirect('wagtailadmin_explore', parent_page.id)
return render(request, 'modeltranslation_copy.html', {
'page': page,
'form': form,
'next': next_url
})