Ejemplo n.º 1
0
    def __init__(self, *args, **kwargs):
        super(AdvancedSettingsForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'navigation_extenders' in self.fields:
            self.fields['navigation_extenders'].widget = forms.Select(
                {}, [('', "---------")] + menu_pool.get_menus_by_attribute("cms_enabled", True))
        if 'application_urls' in self.fields:
            # Prepare a dict mapping the apps by class name ('PollApp') to
            # their app_name attribute ('polls'), if any.
            app_namespaces = {}
            app_configs = {}
            for hook in apphook_pool.get_apphooks():
                app = apphook_pool.get_apphook(hook[0])
                if app.app_name:
                    app_namespaces[hook[0]] = app.app_name
                if app.app_config:
                    app_configs[hook[0]] = app

            self.fields['application_urls'].widget = AppHookSelect(
                attrs={'id': 'application_urls'},
                app_namespaces=app_namespaces
            )
            self.fields['application_urls'].choices = [('', "---------")] + apphook_pool.get_apphooks()

            page_data = self.data if self.data else self.initial
            if app_configs:
                self.fields['application_configs'].widget = ApplicationConfigSelect(
                    attrs={'id': 'application_configs'},
                    app_configs=app_configs)

                if page_data.get('application_urls', False) and page_data['application_urls'] in app_configs:
                    self.fields['application_configs'].choices = [(config.pk, force_text(config)) for config in app_configs[page_data['application_urls']].get_configs()]

                    apphook = page_data.get('application_urls', False)
                    try:
                        config = apphook_pool.get_apphook(apphook).get_configs().get(namespace=self.initial['application_namespace'])
                        self.fields['application_configs'].initial = config.pk
                    except ObjectDoesNotExist:
                        # Provided apphook configuration doesn't exist (anymore),
                        # just skip it
                        # The user will choose another value anyway
                        pass
                else:
                    # If app_config apphook is not selected, drop any value
                    # for application_configs to avoid the field data from
                    # being validated by the field itself
                    try:
                        del self.data['application_configs']
                    except KeyError:
                        pass

        if 'redirect' in self.fields:
            self.fields['redirect'].widget.language = self.fields['language'].initial
Ejemplo n.º 2
0
 def __init__(self, *args, **kwargs):
     super(PageForm, self).__init__(*args, **kwargs)
     self.fields['parent'].widget = HiddenInput()
     self.fields['site'].widget = HiddenInput()
     self.fields['template'].widget = HiddenInput()
     self.fields['language'].widget = HiddenInput()
     if not self.fields['site'].initial:
         self.fields['site'].initial = Site.objects.get_current().pk
     site_id = self.fields['site'].initial
     languages = get_language_tuple(site_id)
     self.fields['language'].choices = languages
     if not self.fields['language'].initial:
         self.fields['language'].initial = get_language()
     if 'page_type' in self.fields:
         try:
             type_root = Page.objects.get(publisher_is_draft=True,
                                          reverse_id=PAGE_TYPES_ID,
                                          site=site_id)
         except Page.DoesNotExist:
             type_root = None
         if type_root:
             language = self.fields['language'].initial
             type_ids = type_root.get_descendants().values_list('pk',
                                                                flat=True)
             titles = Title.objects.filter(page__in=type_ids,
                                           language=language)
             choices = [('', '----')]
             for title in titles:
                 choices.append((title.page_id, title.title))
             self.fields['page_type'].choices = choices
Ejemplo n.º 3
0
class InheritPagePlaceholder(CMSPlugin):
    """
    Provides the ability to inherit plugins for a certain placeholder from an
    associated "parent" page instance
    """
    from_page = PageField(null=True,
                          blank=True,
                          help_text=_(
                              "Choose a page to include its plugins into this "
                              "placeholder, empty will choose current page"))

    from_language = models.CharField(
        _("language"),
        max_length=5,
        choices=get_language_tuple(),
        blank=True,
        null=True,
        help_text=_("Optional: the language of the plugins "
                    "you want"))

    # TODO: Remove this once < 3.3.1 support is dropped
    cmsplugin_ptr = models.OneToOneField(
        to=CMSPlugin,
        parent_link=True,
        related_name='djangocms_inherit_inheritpageplaceholder',
    )

    def copy_relations(self, oldinstance):
        if oldinstance.from_page_id:
            self.from_page_id = oldinstance.from_page_id
Ejemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        super(AdvancedSettingsForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'navigation_extenders' in self.fields:
            self.fields['navigation_extenders'].widget = forms.Select({},
                [('', "---------")] + menu_pool.get_menus_by_attribute("cms_enabled", True))
        if 'application_urls' in self.fields:
            # Prepare a dict mapping the apps by class name ('PollApp') to
            # their app_name attribute ('polls'), if any.
            app_namespaces = {}
            for app_class in apphook_pool.apps.keys():
                app = apphook_pool.apps[app_class]
                if app.app_name:
                    app_namespaces[app_class] = app.app_name

            self.fields['application_urls'].widget = AppHookSelect(
                attrs={'id':'application_urls'},
                app_namespaces=app_namespaces,
            )
            self.fields['application_urls'].choices = [('', "---------")] + apphook_pool.get_apphooks()

        if 'redirect' in self.fields:
            self.fields['redirect'].widget.language = self.fields['language'].initial
Ejemplo n.º 5
0
    def __init__(self, *args, **kwargs):
        super(AdvancedSettingsForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'navigation_extenders' in self.fields:
            self.fields['navigation_extenders'].widget = forms.Select({},
                [('', "---------")] + menu_pool.get_menus_by_attribute("cms_enabled", True))
        if 'application_urls' in self.fields:
            # Prepare a dict mapping the apps by class name ('PollApp') to
            # their app_name attribute ('polls'), if any.
            app_namespaces = {}
            for hook in apphook_pool.get_apphooks():
                app = apphook_pool.get_apphook(hook[0])
                if app.app_name:
                    app_namespaces[hook[0]] = app.app_name

            self.fields['application_urls'].widget = AppHookSelect(
                attrs={'id':'application_urls'},
                app_namespaces=app_namespaces,
            )
            self.fields['application_urls'].choices = [('', "---------")] + apphook_pool.get_apphooks()

        if 'redirect' in self.fields:
            self.fields['redirect'].widget.language = self.fields['language'].initial
Ejemplo n.º 6
0
 def __init__(self, *args, **kwargs):
     super(PageForm, self).__init__(*args, **kwargs)
     self.fields['parent'].widget = HiddenInput()
     self.fields['site'].widget = HiddenInput()
     self.fields['template'].widget = HiddenInput()
     self.fields['language'].widget = HiddenInput()
     if not self.fields['site'].initial:
         self.fields['site'].initial = Site.objects.get_current().pk
     site_id = self.fields['site'].initial
     languages = get_language_tuple(site_id)
     self.fields['language'].choices = languages
     if not self.fields['language'].initial:
         self.fields['language'].initial = get_language()
     if 'page_type' in self.fields:
         try:
             type_root = Page.objects.get(publisher_is_draft=True, reverse_id=PAGE_TYPES_ID, site=site_id)
         except Page.DoesNotExist:
             type_root = None
         if type_root:
             language = self.fields['language'].initial
             type_ids = type_root.get_descendants().values_list('pk', flat=True)
             titles = Title.objects.filter(page__in=type_ids, language=language)
             choices = [('', '----')]
             for title in titles:
                 choices.append((title.page_id, title.title))
             self.fields['page_type'].choices = choices
Ejemplo n.º 7
0
 def __init__(self, *args, **kwargs):
     """
     Override the language choices to ensure only those available on a given site are shown.
     """
     super().__init__(*args, **kwargs)
     site = Site.objects.get_current()
     self.fields["language"].choices = tuple(
         get_language_tuple(site_id=site.pk))
Ejemplo n.º 8
0
 def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
     # add context variables
     filled_languages = []
     if obj:
         filled_languages = [t[0] for t in obj.title_set.filter(title__isnull=False).values_list('language')]
     allowed_languages = [lang[0] for lang in get_language_tuple()]
     context.update({
         'filled_languages': [lang for lang in filled_languages if lang in allowed_languages],
     })
     return super(ArticleAdmin, self).render_change_form(request, context, add, change, form_url, obj)
Ejemplo n.º 9
0
 def add_language_menu(self):
     if settings.USE_I18N and not self._language_menu:
         self._language_menu = self.toolbar.get_or_create_menu(LANGUAGE_MENU_IDENTIFIER, _('Language'), position=-1)
         language_changer = getattr(self.request, '_language_changer', DefaultLanguageChanger(self.request))
         for code, name in get_language_tuple(self.current_site.pk):
             try:
                 url = language_changer(code)
             except NoReverseMatch:
                 url = DefaultLanguageChanger(self.request)(code)
             self._language_menu.add_link_item(name, url=url, active=self.current_lang == code)
Ejemplo n.º 10
0
 def add_language_menu(self):
     if settings.USE_I18N and not self._language_menu:
         self._language_menu = self.toolbar.get_or_create_menu(LANGUAGE_MENU_IDENTIFIER, _('Language'), position=-1)
         language_changer = getattr(self.request, '_language_changer', DefaultLanguageChanger(self.request))
         for code, name in get_language_tuple(self.current_site.pk):
             try:
                 url = language_changer(code)
             except NoReverseMatch:
                 url = DefaultLanguageChanger(self.request)(code)
             self._language_menu.add_link_item(name, url=url, active=self.current_lang == code)
Ejemplo n.º 11
0
    def change_language_menu(self):
        if self.toolbar.edit_mode and self.page:
            language_menu = self.toolbar.get_menu(LANGUAGE_MENU_IDENTIFIER)
            if not language_menu:
                return None

            languages = get_language_tuple(self.current_site.pk)
            languages_dict = dict(languages)

            remove = [(code, languages_dict.get(code, code))
                      for code in self.page.get_languages()]
            add = [l for l in languages if l not in remove]
            copy = [(code, name) for code, name in languages
                    if code != self.current_lang and (code, name) in remove]

            if add:
                language_menu.add_break(ADD_PAGE_LANGUAGE_BREAK)
                page_change_url = admin_reverse('cms_page_change',
                                                args=(self.page.pk, ))
                title = _('Add %(language)s Translation')
                for code, name in add:
                    url = add_url_parameters(page_change_url, language=code)
                    language_menu.add_modal_item(title % {'language': name},
                                                 url=url)

            if remove:
                language_menu.add_break(REMOVE_PAGE_LANGUAGE_BREAK)
                translation_delete_url = admin_reverse(
                    'cms_page_delete_translation', args=(self.page.pk, ))
                title = _('Delete %(language)s Translation')
                disabled = len(remove) == 1
                for code, name in remove:
                    url = add_url_parameters(translation_delete_url,
                                             language=code)
                    language_menu.add_modal_item(title % {'language': name},
                                                 url=url,
                                                 disabled=disabled)

            if copy:
                language_menu.add_break(COPY_PAGE_LANGUAGE_BREAK)
                page_copy_url = admin_reverse('cms_page_copy_language',
                                              args=(self.page.pk, ))
                title = _('Copy all plugins from %s')
                question = _('Are you sure you want copy all plugins from %s?')
                for code, name in copy:
                    language_menu.add_ajax_item(
                        title % name,
                        action=page_copy_url,
                        data={
                            'source_language': code,
                            'target_language': self.current_lang
                        },
                        question=question % name,
                        on_success=self.toolbar.REFRESH_PAGE)
Ejemplo n.º 12
0
    def __init__(self, *args, **kwargs):
        # Dates are not language dependent, so let's just fake the language to
        # make the ModelAdmin happy
        super(PublicationDatesForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
Ejemplo n.º 13
0
 def update_language_tab_context(self, request, context=None):
     if not context:
         context = {}
     language = get_language_from_request(request)
     languages = get_language_tuple()
     context.update({
         'language': language,
         'languages': languages,
         'language_tabs': languages,
         'show_language_tabs': len(list(languages)) > 1,
     })
     return context
Ejemplo n.º 14
0
 def update_language_tab_context(self, request, context=None):
     if not context:
         context = {}
     language = get_language_from_request(request)
     languages = get_language_tuple()
     context.update({
         'language': language,
         'languages': languages,
         'language_tabs': languages,
         'show_language_tabs': len(list(languages)) > 1,
     })
     return context
Ejemplo n.º 15
0
    def __init__(self, *args, **kwargs):
        # Dates are not language dependent, so let's just fake the language to
        # make the ModelAdmin happy
        super(PublicationDatesForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
Ejemplo n.º 16
0
 def __init__(self, *args, **kwargs):
     super(PageForm, self).__init__(*args, **kwargs)
     self.fields['parent'].widget = HiddenInput()
     self.fields['site'].widget = HiddenInput()
     self.fields['template'].widget = HiddenInput()
     self.fields['language'].widget = HiddenInput()
     if not self.fields['site'].initial:
         self.fields['site'].initial = Site.objects.get_current().pk
     site_id = self.fields['site'].initial
     languages = get_language_tuple(site_id)
     self.fields['language'].choices = languages
     if not self.fields['language'].initial:
         self.fields['language'].initial = get_language()
Ejemplo n.º 17
0
class PublicationDatesForm(forms.ModelForm):
    language = forms.ChoiceField(
        label=_("Language"),
        choices=get_language_tuple(),
        help_text=_('The current language of the content fields.'))

    def __init__(self, *args, **kwargs):
        super(PublicationDatesForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = forms.HiddenInput()

    class Meta:
        model = Article
        fields = ['publication_date', 'publication_end_date']
Ejemplo n.º 18
0
class InheritPagePlaceholder(CMSPlugin):
    """
    Provides the ability to inherit plugins for a certain placeholder from an
    associated "parent" page instance
    """
    from_page = PageField(
        null=True, blank=True,
        help_text=_("Choose a page to include its plugins into this "
                    "placeholder, empty will choose current page"))

    from_language = models.CharField(
        _("language"), max_length=5, choices=get_language_tuple(), blank=True,
        null=True, help_text=_("Optional: the language of the plugins "
                               "you want"))
Ejemplo n.º 19
0
    def __init__(self, *args, **kwargs):
        super(AdvancedSettingsForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'navigation_extenders' in self.fields:
            self.fields['navigation_extenders'].widget = forms.Select({},
                [('', "---------")] + menu_pool.get_menus_by_attribute("cms_enabled", True))
        if 'application_urls' in self.fields:
            self.fields['application_urls'].choices = [('', "---------")] + apphook_pool.get_apphooks()
Ejemplo n.º 20
0
 def __init__(self, *args, **kwargs):
     super(PageAddForm, self).__init__(*args, **kwargs)
     self.fields['parent'].widget = HiddenInput() 
     self.fields['site'].widget = HiddenInput()
     if not self.fields['site'].initial:
         self.fields['site'].initial = Site.objects.get_current().pk
     site_id = self.fields['site'].initial
     languages = get_language_tuple(site_id)
     self.fields['language'].choices = languages
     if not self.fields['language'].initial:
         self.fields['language'].initial = get_language()
     if (self.fields['parent'].initial and
         get_cms_setting('TEMPLATE_INHERITANCE') in
         [name for name, value in get_cms_setting('TEMPLATES')]):
         # non-root pages default to inheriting their template
         self.fields['template'].initial = constants.TEMPLATE_INHERITANCE_MAGIC
Ejemplo n.º 21
0
class ArticleForm(forms.ModelForm):
    language = forms.ChoiceField(
        label=_('Language'),
        choices=get_language_tuple(),
        help_text=_('The current language of the content fields.'))
    title = Title._meta.get_field('title').formfield()
    slug = Title._meta.get_field('slug').formfield()
    description = Title._meta.get_field('description').formfield()
    page_title = Title._meta.get_field('page_title').formfield()
    menu_title = Title._meta.get_field('menu_title').formfield()
    meta_description = Title._meta.get_field('meta_description').formfield()
    image = Title._meta.get_field('image').formfield()

    class Meta:
        model = Article
        fields = ['tree', 'template', 'login_required']

    def __init__(self, *args, **kwargs):
        super(ArticleForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = forms.HiddenInput()
        if self.fields['tree'].widget.choices.queryset.count() == 1:
            self.fields['tree'].initial = self.fields[
                'tree'].widget.choices.queryset.first()
            self.fields['tree'].widget = forms.HiddenInput()

    def clean(self):
        cleaned_data = self.cleaned_data
        slug = cleaned_data.get('slug', '')

        article = self.instance
        lang = cleaned_data.get('language', None)
        # No language, can not go further, but validation failed already
        if not lang:
            return cleaned_data
        tree = self.cleaned_data.get('tree', None)
        if tree and not is_valid_article_slug(article, lang, slug):
            self._errors['slug'] = ErrorList(
                [_('Another article with this slug already exists')])
            del cleaned_data['slug']
        return cleaned_data

    def clean_slug(self):
        slug = slugify(self.cleaned_data['slug'])
        if not slug:
            raise ValidationError(_('Slug must not be empty.'))
        return settings.CMS_ARTICLES_SLUG_FORMAT.format(
            now=self.instance.creation_date or now(), slug=slug)
Ejemplo n.º 22
0
    def override_language_switcher(self):
        language_menu = self.toolbar.get_menu(LANGUAGE_MENU_IDENTIFIER,
                                              _('Language'))
        # Remove all existing language links
        # remove_item uses `items` attribute so we have to copy object
        for _item in copy(language_menu.items):
            language_menu.remove_item(item=_item)

        for code, name in get_language_tuple(self.current_site.pk):
            # Showing only existing translation. For versioning it will be only
            # published translation
            alias_content = self.toolbar.obj.alias.get_content(language=code)
            if alias_content:
                with force_language(code):
                    url = alias_content.get_absolute_url()
                language_menu.add_link_item(name,
                                            url=url,
                                            active=self.current_lang == code)
Ejemplo n.º 23
0
class PublicationDatesForm(forms.ModelForm):
    language = forms.ChoiceField(label=_("Language"), choices=get_language_tuple(),
                                 help_text=_('The current language of the content fields.'))

    def __init__(self, *args, **kwargs):
        # Dates are not language dependent, so let's just fake the language to
        # make the ModelAdmin happy
        super(PublicationDatesForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()

    class Meta:
        model = Page
        fields = ['site', 'publication_date', 'publication_end_date']
Ejemplo n.º 24
0
    def override_language_menu(self):
        """
        Override the default language menu for pages that are versioned.
        The default language menu is too generic so for pages we need to replace it.
        """
        # Only override the menu if a page can be found
        if settings.USE_I18N and self.page:
            language_menu = self.toolbar.get_menu(LANGUAGE_MENU_IDENTIFIER,
                                                  _('Language'))

            # remove_item uses `items` attribute so we have to copy object
            for _item in copy(language_menu.items):
                language_menu.remove_item(item=_item)

            for code, name in get_language_tuple(self.current_site.pk):
                # Get the pagw content, it could be draft too!
                page_content = self.get_page_content(language=code)
                if page_content:
                    url = get_object_preview_url(page_content, code)
                    language_menu.add_link_item(
                        name, url=url, active=self.current_lang == code)
Ejemplo n.º 25
0
class Migration(migrations.Migration):

    dependencies = [
        ('cms', '__first__'),
    ]

    operations = [
        migrations.CreateModel(
            name='InheritPagePlaceholder',
            fields=[
                ('cmsplugin_ptr',
                 models.OneToOneField(serialize=False,
                                      parent_link=True,
                                      auto_created=True,
                                      to='cms.CMSPlugin',
                                      primary_key=True,
                                      on_delete=models.CASCADE)),
                ('from_language',
                 models.CharField(
                     help_text='Optional: the language of the plugins you want',
                     blank=True,
                     max_length=5,
                     choices=get_language_tuple(),
                     verbose_name='language',
                     null=True)),
                ('from_page',
                 models.ForeignKey(
                     help_text=
                     'Choose a page to include its plugins into this placeholder, empty will choose current page',
                     blank=True,
                     to='cms.Page',
                     null=True,
                     on_delete=models.CASCADE)),
            ],
            options={
                'abstract': False,
            },
            bases=('cms.cmsplugin', ),
        ),
    ]
Ejemplo n.º 26
0
 def render_change_form(self,
                        request,
                        context,
                        add=False,
                        change=False,
                        form_url='',
                        obj=None):
     # add context variables
     filled_languages = []
     if obj:
         filled_languages = [
             t[0] for t in obj.title_set.filter(
                 title__isnull=False).values_list('language')
         ]
     allowed_languages = [lang[0] for lang in get_language_tuple()]
     context.update({
         'filled_languages':
         [lang for lang in filled_languages if lang in allowed_languages],
     })
     return super(ArticleAdmin,
                  self).render_change_form(request, context, add, change,
                                           form_url, obj)
Ejemplo n.º 27
0
    def change_language_menu(self):
        if self.toolbar.edit_mode and self.page:
            language_menu = self.toolbar.get_menu(LANGUAGE_MENU_IDENTIFIER)
            if not language_menu:
                return None

            languages = get_language_tuple(self.current_site.pk)
            languages_dict = dict(languages)

            remove = [(code, languages_dict.get(code, code)) for code in self.page.get_languages()]
            add = [l for l in languages if l not in remove]
            copy = [(code, name) for code, name in languages if code != self.current_lang and (code, name) in remove]

            if add:
                language_menu.add_break(ADD_PAGE_LANGUAGE_BREAK)
                page_change_url = admin_reverse('cms_page_change', args=(self.page.pk,))
                title = _('Add %(language)s Translation')
                for code, name in add:
                    url = add_url_parameters(page_change_url, language=code)
                    language_menu.add_modal_item(title % {'language': name}, url=url)

            if remove:
                language_menu.add_break(REMOVE_PAGE_LANGUAGE_BREAK)
                translation_delete_url = admin_reverse('cms_page_delete_translation', args=(self.page.pk,))
                title = _('Delete %(language)s Translation')
                disabled = len(remove) == 1
                for code, name in remove:
                    url = add_url_parameters(translation_delete_url, language=code)
                    language_menu.add_modal_item(title % {'language': name}, url=url, disabled=disabled)

            if copy:
                language_menu.add_break(COPY_PAGE_LANGUAGE_BREAK)
                page_copy_url = admin_reverse('cms_page_copy_language', args=(self.page.pk,))
                title = _('Copy all plugins from %s')
                question = _('Are you sure you want copy all plugins from %s?')
                for code, name in copy:
                    language_menu.add_ajax_item(title % name, action=page_copy_url,
                                                data={'source_language': code, 'target_language': self.current_lang},
                                                question=question % name, on_success=self.toolbar.REFRESH_PAGE)
Ejemplo n.º 28
0
class PageForm(forms.ModelForm):
    title = forms.CharField(label=_("Title"), widget=forms.TextInput(),
                            help_text=_('The default title'))
    slug = forms.CharField(label=_("Slug"), widget=forms.TextInput(),
                           help_text=_('The part of the title that is used in the URL'))
    menu_title = forms.CharField(label=_("Menu Title"), widget=forms.TextInput(),
                                 help_text=_('Overwrite what is displayed in the menu'), required=False)
    page_title = forms.CharField(label=_("Page Title"), widget=forms.TextInput(),
                                 help_text=_('Overwrites what is displayed at the top of your browser or in bookmarks'),
                                 required=False)
    meta_description = forms.CharField(label='Description meta tag', required=False,
                                       widget=forms.Textarea(attrs={'maxlength': '155', 'rows': '4'}),
                                       help_text=_('A description of the page used by search engines.'),
                                       max_length=155)
    language = forms.ChoiceField(label=_("Language"), choices=get_language_tuple(),
                                 help_text=_('The current language of the content fields.'))


    class Meta:
        model = Page
        fields = ["parent", "site", 'template']

    def __init__(self, *args, **kwargs):
        super(PageForm, self).__init__(*args, **kwargs)
        self.fields['parent'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        self.fields['template'].widget = HiddenInput()
        self.fields['language'].widget = HiddenInput()
        if not self.fields['site'].initial:
            self.fields['site'].initial = Site.objects.get_current().pk
        site_id = self.fields['site'].initial
        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()

    def clean(self):
        cleaned_data = self.cleaned_data
        slug = cleaned_data.get('slug', '')

        page = self.instance
        lang = cleaned_data.get('language', None)
        # No language, can not go further, but validation failed already
        if not lang:
            return cleaned_data

        if 'parent' not in cleaned_data:
            cleaned_data['parent'] = None
        parent = cleaned_data.get('parent', None)

        try:
            site = self.cleaned_data.get('site', Site.objects.get_current())
        except Site.DoesNotExist:
            raise ValidationError("No site found for current settings.")

        if parent and parent.site != site:
            raise ValidationError("Site doesn't match the parent's page site")

        if site and not is_valid_page_slug(page, parent, lang, slug, site):
            self._errors['slug'] = ErrorList([_('Another page with this slug already exists')])
            del cleaned_data['slug']
        if self.instance and self.instance.published and page.title_set.count():
            #Check for titles attached to the page makes sense only because
            #AdminFormsTests.test_clean_overwrite_url validates the form with when no page instance available
            #Looks like just a theoretical corner case
            try:
                title = page.get_title_obj(lang, fallback=False)
            except titlemodels.Title.DoesNotExist:
                title = None
            if title and not isinstance(title, titlemodels.EmptyTitle) and slug:
                oldslug = title.slug
                title.slug = slug
                title.save()
                try:
                    is_valid_url(title.path, page)
                except ValidationError:
                    exc = sys.exc_info()[0]
                    title.slug = oldslug
                    title.save()
                    if 'slug' in cleaned_data:
                        del cleaned_data['slug']
                    self._errors['slug'] = ErrorList(exc.messages)
        return cleaned_data

    def clean_slug(self):
        slug = slugify(self.cleaned_data['slug'])
        if not slug:
            raise ValidationError("Slug must not be empty.")
        return slug

    def clean_language(self):
        language = self.cleaned_data['language']
        if not language in get_language_list():
            raise ValidationError("Given language does not match language settings.")
        return language
Ejemplo n.º 29
0
 def lookups(self, request, model_admin):
     return get_language_tuple()
Ejemplo n.º 30
0
class AdvancedSettingsForm(forms.ModelForm):
    application_urls = forms.ChoiceField(label=_('Application'),
                                         choices=(), required=False,
                                         help_text=_('Hook application to this page.'))
    overwrite_url = forms.CharField(label=_('Overwrite URL'), max_length=255, required=False,
                                    help_text=_('Keep this field empty if standard path should be used.'))

    redirect = forms.CharField(label=_('Redirect'), max_length=255, required=False,
                               help_text=_('Redirects to this URL.'))
    language = forms.ChoiceField(label=_("Language"), choices=get_language_tuple(),
                                 help_text=_('The current language of the content fields.'))

    def __init__(self, *args, **kwargs):
        super(AdvancedSettingsForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'navigation_extenders' in self.fields:
            self.fields['navigation_extenders'].widget = forms.Select({},
                [('', "---------")] + menu_pool.get_menus_by_attribute("cms_enabled", True))
        if 'application_urls' in self.fields:
            self.fields['application_urls'].choices = [('', "---------")] + apphook_pool.get_apphooks()

    def clean(self):
        cleaned_data = super(AdvancedSettingsForm, self).clean()
        if 'reverse_id' in self.fields:
            id = cleaned_data['reverse_id']
            site_id = cleaned_data['site']
            if id:
                if Page.objects.filter(reverse_id=id, site=site_id, publisher_is_draft=True).exclude(
                        pk=self.instance.pk).count():
                    self._errors['reverse_id'] = self.error_class(
                        [_('A page with this reverse URL id exists already.')])
        apphook = cleaned_data['application_urls']
        namespace = cleaned_data['application_namespace']
        if apphook:
            apphook_pool.discover_apps()
            if apphook_pool.apps[apphook].app_name and not namespace:
                self._errors['application_urls'] = ErrorList(
                    [_('You selected an apphook with an "app_name". You must enter a namespace.')])
        if namespace and not apphook:
            self._errors['application_namespace'] = ErrorList(
                [_("If you enter a namespace you need an application url as well.")])
        return cleaned_data

    def clean_overwrite_url(self):
        if 'overwrite_url' in self.fields:
            url = self.cleaned_data['overwrite_url']
            is_valid_url(url, self.instance)
            return url

    class Meta:
        model = Page
        fields = [
            'site', 'template', 'reverse_id', 'overwrite_url', 'redirect', 'soft_root', 'navigation_extenders',
            'application_urls', 'application_namespace'
        ]
Ejemplo n.º 31
0
class AdvancedSettingsForm(forms.ModelForm):
    from cms.forms.fields import PageSmartLinkField
    application_urls = forms.ChoiceField(
        label=_('Application'),
        choices=(),
        required=False,
        help_text=_('Hook application to this page.'))
    overwrite_url = forms.CharField(
        label=_('Overwrite URL'),
        max_length=255,
        required=False,
        help_text=_('Keep this field empty if standard path should be used.'))

    xframe_options = forms.ChoiceField(
        choices=Page._meta.get_field('xframe_options').choices,
        label=_('X Frame Options'),
        help_text=_(
            'Whether this page can be embedded in other pages or websites'),
        initial=Page._meta.get_field('xframe_options').default,
        required=False)

    redirect = PageSmartLinkField(label=_('Redirect'),
                                  required=False,
                                  help_text=_('Redirects to this URL.'),
                                  placeholder_text=_('Start typing...'))

    language = forms.ChoiceField(
        label=_("Language"),
        choices=get_language_tuple(),
        help_text=_('The current language of the content fields.'))

    def __init__(self, *args, **kwargs):
        super(AdvancedSettingsForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'navigation_extenders' in self.fields:
            self.fields['navigation_extenders'].widget = forms.Select(
                {}, [('', "---------")] +
                menu_pool.get_menus_by_attribute("cms_enabled", True))
        if 'application_urls' in self.fields:
            self.fields['application_urls'].choices = [
                ('', "---------")
            ] + apphook_pool.get_apphooks()

        if 'redirect' in self.fields:
            self.fields['redirect'].widget.language = self.fields[
                'language'].initial

    def clean(self):
        cleaned_data = super(AdvancedSettingsForm, self).clean()
        if 'reverse_id' in self.fields:
            id = cleaned_data['reverse_id']
            site_id = cleaned_data['site']
            if id:
                if Page.objects.filter(reverse_id=id,
                                       site=site_id,
                                       publisher_is_draft=True).exclude(
                                           pk=self.instance.pk).count():
                    self._errors['reverse_id'] = self.error_class(
                        [_('A page with this reverse URL id exists already.')])
        apphook = cleaned_data.get('application_urls', None)
        namespace = cleaned_data.get('application_namespace', None)
        if apphook:
            apphook_pool.discover_apps()
            if apphook_pool.apps[apphook].app_name and not namespace:
                self._errors['application_urls'] = ErrorList([
                    _('You selected an apphook with an "app_name". You must enter a instance name.'
                      )
                ])
        if namespace and not apphook:
            self._errors['application_namespace'] = ErrorList([
                _("If you enter an instance name you need an application url as well."
                  )
            ])
        return cleaned_data

    def clean_application_namespace(self):
        namespace = self.cleaned_data['application_namespace']
        if namespace and Page.objects.filter(
                publisher_is_draft=True,
                application_namespace=namespace).exclude(
                    pk=self.instance.pk).count():
            raise ValidationError(
                _('A instance name with this name already exists.'))
        return namespace

    def clean_xframe_options(self):
        if 'xframe_options' not in self.fields:
            return  # nothing to do, field isn't present

        xframe_options = self.cleaned_data['xframe_options']
        if xframe_options == '':
            return Page._meta.get_field('xframe_options').default

        return xframe_options

    def clean_overwrite_url(self):
        if 'overwrite_url' in self.fields:
            url = self.cleaned_data['overwrite_url']
            is_valid_url(url, self.instance)
            return url

    class Meta:
        model = Page
        fields = [
            'site',
            'template',
            'reverse_id',
            'overwrite_url',
            'redirect',
            'soft_root',
            'navigation_extenders',
            'application_urls',
            'application_namespace',
            "xframe_options",
        ]
Ejemplo n.º 32
0
    def populate(self):
        self.page = get_page_draft(self.request.current_page)
        config = self.__get_services_config()
        if not config:
            # Do nothing if there is no services app_config to work with
            return

        user = getattr(self.request, 'user', None)
        try:
            view_name = self.request.resolver_match.view_name
        except AttributeError:
            view_name = None

        if user and view_name:
            language = get_language_from_request(self.request, check_path=True)

            # get existing admin menu
            admin_menu = self.toolbar.get_or_create_menu(ADMIN_MENU_IDENTIFIER)

            # add new Services item
            admin_menu.add_sideframe_item(_('Services'),
                                          url='/admin/js_services/service/',
                                          position=0)

            # If we're on an Service detail page, then get the service
            if view_name == '{0}:service-detail'.format(config.namespace):
                obj = get_object_from_request(Service, self.request)
            else:
                obj = None

            menu = self.toolbar.get_or_create_menu('services-app',
                                                   config.get_app_title())

            change_config_perm = user.has_perm(
                'js_services.change_servicesconfig')
            add_config_perm = user.has_perm('js_services.add_servicesconfig')
            config_perms = [change_config_perm, add_config_perm]

            change_service_perm = user.has_perm('js_services.change_service')
            delete_service_perm = user.has_perm('js_services.delete_service')
            add_service_perm = user.has_perm('js_services.add_service')
            service_perms = [
                change_service_perm,
                add_service_perm,
                delete_service_perm,
            ]

            if change_config_perm:
                url_args = {}
                if language:
                    url_args = {
                        'language': language,
                    }
                url = get_admin_url('js_services_servicesconfig_change', [
                    config.pk,
                ], **url_args)
                menu.add_modal_item(_('Configure addon'), url=url)

            if any(config_perms) and any(service_perms):
                menu.add_break()

            if change_service_perm:
                url_args = {}
                if config:
                    url_args = {'sections__id__exact': config.pk}
                url = get_admin_url('js_services_service_changelist',
                                    **url_args)
                menu.add_sideframe_item(_('Service list'), url=url)

            if add_service_perm:
                url_args = {
                    'sections': config.pk,
                    'owner': user.pk,
                }
                if language:
                    url_args.update({
                        'language': language,
                    })
                url = get_admin_url('js_services_service_add', **url_args)
                menu.add_modal_item(_('Add new service'), url=url)

            if change_service_perm and obj:
                url_args = {}
                if language:
                    url_args = {
                        'language': language,
                    }
                url = get_admin_url('js_services_service_change', [
                    obj.pk,
                ], **url_args)
                menu.add_modal_item(_('Edit this service'),
                                    url=url,
                                    active=True)

            if delete_service_perm and obj:
                redirect_url = self.get_on_delete_redirect_url(
                    obj, language=language)
                url = get_admin_url('js_services_service_delete', [
                    obj.pk,
                ])
                menu.add_modal_item(_('Delete this service'),
                                    url=url,
                                    on_close=redirect_url)

        if settings.USE_I18N:  # and not self._language_menu:
            if obj:
                self._language_menu = self.toolbar.get_or_create_menu(
                    LANGUAGE_MENU_IDENTIFIER, _('Language'), position=-1)
                self._language_menu.items = []
                languages = get_language_dict(self.current_site.pk)
                page_languages = self.page.get_languages()
                remove = []

                for code, name in get_language_tuple():
                    if code in obj.get_available_languages():
                        remove.append((code, name))
                        try:
                            url = obj.get_absolute_url(code)
                        except NoReverseMatch:
                            url = None
                        if url and code in page_languages:
                            self._language_menu.add_link_item(
                                name,
                                url=url,
                                active=self.current_lang == code)

                if self.toolbar.edit_mode_active:
                    add = [l for l in languages.items() if l not in remove]
                    copy = [
                        (code, name) for code, name in languages.items()
                        if code != self.current_lang and (code, name) in remove
                    ]

                    if (add or len(remove) > 1
                            or copy) and change_service_perm:
                        self._language_menu.add_break(ADD_OBJ_LANGUAGE_BREAK)

                        if add:
                            add_plugins_menu = self._language_menu.get_or_create_menu(
                                '{0}-add-trans'.format(
                                    LANGUAGE_MENU_IDENTIFIER),
                                _('Add Translation'))
                            for code, name in add:
                                url_args = {}
                                url = '%s?language=%s' % (get_admin_url(
                                    'js_services_service_change', [obj.pk], **
                                    url_args), code)
                                add_plugins_menu.add_modal_item(name, url=url)

                        if len(remove) > 1:
                            remove_plugins_menu = self._language_menu.get_or_create_menu(
                                '{0}-del-trans'.format(
                                    LANGUAGE_MENU_IDENTIFIER),
                                _('Delete Translation'))
                            for code, name in remove:
                                url = get_admin_url(
                                    'js_services_service_delete_translation',
                                    [obj.pk, code])
                                remove_plugins_menu.add_modal_item(name,
                                                                   url=url)

                        if copy:
                            copy_plugins_menu = self._language_menu.get_or_create_menu(
                                '{0}-copy-trans'.format(
                                    LANGUAGE_MENU_IDENTIFIER),
                                _('Copy all plugins'))
                            title = _('from %s')
                            question = _(
                                'Are you sure you want to copy all plugins from %s?'
                            )
                            url = get_admin_url(
                                'js_services_service_copy_language', [obj.pk])
                            for code, name in copy:
                                copy_plugins_menu.add_ajax_item(
                                    title % name,
                                    action=url,
                                    data={
                                        'source_language': code,
                                        'target_language': self.current_lang
                                    },
                                    question=question % name,
                                    on_success=self.toolbar.REFRESH_PAGE)
Ejemplo n.º 33
0
class PageAddForm(forms.ModelForm):
    title = forms.CharField(label=_("Title"), widget=forms.TextInput(),
        help_text=_('The default title'))
    slug = forms.CharField(label=_("Slug"), widget=forms.TextInput(),
        help_text=_('The part of the title that is used in the URL'))
    language = forms.ChoiceField(label=_("Language"), choices=get_language_tuple(),
        help_text=_('The current language of the content fields.'))
    
    class Meta:
        model = Page
        exclude = ["created_by", "changed_by", "placeholders"]
    
    def __init__(self, *args, **kwargs):
        super(PageAddForm, self).__init__(*args, **kwargs)
        self.fields['parent'].widget = HiddenInput() 
        self.fields['site'].widget = HiddenInput()
        if not self.fields['site'].initial:
            self.fields['site'].initial = Site.objects.get_current().pk
        site_id = self.fields['site'].initial
        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if (self.fields['parent'].initial and
            get_cms_setting('TEMPLATE_INHERITANCE') in
            [name for name, value in get_cms_setting('TEMPLATES')]):
            # non-root pages default to inheriting their template
            self.fields['template'].initial = constants.TEMPLATE_INHERITANCE_MAGIC
        
    def clean(self):
        cleaned_data = self.cleaned_data
        slug = cleaned_data.get('slug', '')
        
        page = self.instance
        lang = cleaned_data.get('language', None)
        # No language, can not go further, but validation failed already
        if not lang: 
            return cleaned_data
        
        if 'parent' not in cleaned_data:
            cleaned_data['parent'] = None
        parent = cleaned_data.get('parent', None)
        
        try:
            site = self.cleaned_data.get('site', Site.objects.get_current())
        except Site.DoesNotExist:
            site = None
            raise ValidationError("No site found for current settings.")

        if parent and parent.site != site:
            raise ValidationError("Site doesn't match the parent's page site")
        
        if site and not is_valid_page_slug(page, parent, lang, slug, site):
            self._errors['slug'] = ErrorList([_('Another page with this slug already exists')])
            del cleaned_data['slug']
        if self.cleaned_data.get('published') and page.title_set.count():
            #Check for titles attached to the page makes sense only because
            #AdminFormsTests.test_clean_overwrite_url validates the form with when no page instance available
            #Looks like just a theoretical corner case
            title = page.get_title_obj(lang)
            if title and slug:
                oldslug = title.slug
                title.slug = slug
                title.save()
                try:
                    is_valid_url(title.path,page)
                except ValidationError,e:
                    title.slug = oldslug
                    title.save()
                    if 'slug' in cleaned_data:
                        del cleaned_data['slug']
                    self._errors['slug'] = ErrorList(e.messages)
        return cleaned_data
Ejemplo n.º 34
0
class PageForm(forms.ModelForm):
    language = forms.ChoiceField(
        label=_("Language"),
        choices=get_language_tuple(),
        help_text=_('The current language of the content fields.'))
    page_type = forms.ChoiceField(label=_("Page type"), required=False)
    title = forms.CharField(label=_("Title"),
                            widget=forms.TextInput(),
                            help_text=_('The default title'))
    slug = forms.CharField(
        label=_("Slug"),
        widget=forms.TextInput(),
        help_text=_('The part of the title that is used in the URL'))
    menu_title = forms.CharField(
        label=_("Menu Title"),
        widget=forms.TextInput(),
        help_text=_('Overwrite what is displayed in the menu'),
        required=False)
    page_title = forms.CharField(
        label=_("Page Title"),
        widget=forms.TextInput(),
        help_text=
        _('Overwrites what is displayed at the top of your browser or in bookmarks'
          ),
        required=False)
    meta_description = forms.CharField(
        label=_('Description meta tag'),
        required=False,
        widget=forms.Textarea(attrs={
            'maxlength': '155',
            'rows': '4'
        }),
        help_text=_('A description of the page used by search engines.'),
        max_length=155)

    class Meta:
        model = Page
        fields = ["parent", "site", 'template']

    def __init__(self, *args, **kwargs):
        super(PageForm, self).__init__(*args, **kwargs)
        self.fields['parent'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        self.fields['template'].widget = HiddenInput()
        self.fields['language'].widget = HiddenInput()
        if not self.fields['site'].initial:
            self.fields['site'].initial = Site.objects.get_current().pk
        site_id = self.fields['site'].initial
        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'page_type' in self.fields:
            try:
                type_root = Page.objects.get(publisher_is_draft=True,
                                             reverse_id=PAGE_TYPES_ID,
                                             site=site_id)
            except Page.DoesNotExist:
                type_root = None
            if type_root:
                language = self.fields['language'].initial
                type_ids = type_root.get_descendants().values_list('pk',
                                                                   flat=True)
                titles = Title.objects.filter(page__in=type_ids,
                                              language=language)
                choices = [('', '----')]
                for title in titles:
                    choices.append((title.page_id, title.title))
                self.fields['page_type'].choices = choices

    def clean(self):
        cleaned_data = self.cleaned_data

        if self._errors:
            # Form already has errors, best to let those be
            # addressed first.
            return cleaned_data

        slug = cleaned_data['slug']
        lang = cleaned_data['language']
        parent = cleaned_data.get('parent', None)
        site = self.cleaned_data.get('site', Site.objects.get_current())

        page = self.instance

        if parent and parent.site != site:
            raise ValidationError("Site doesn't match the parent's page site")

        if site and not is_valid_page_slug(page, parent, lang, slug, site):
            self._errors['slug'] = ErrorList(
                [_('Another page with this slug already exists')])
            del cleaned_data['slug']

        if page and page.title_set.exists():
            #Check for titles attached to the page makes sense only because
            #AdminFormsTests.test_clean_overwrite_url validates the form with when no page instance available
            #Looks like just a theoretical corner case
            title = page.get_title_obj(lang, fallback=False)
            if title and not isinstance(title, EmptyTitle) and slug:
                oldslug = title.slug
                title.slug = slug
                title.save()
                try:
                    is_valid_url(title.path, page)
                except ValidationError as exc:
                    title.slug = oldslug
                    title.save()
                    if 'slug' in cleaned_data:
                        del cleaned_data['slug']
                    if hasattr(exc, 'messages'):
                        errors = exc.messages
                    else:
                        errors = [force_text(exc.message)]
                    self._errors['slug'] = ErrorList(errors)
        return cleaned_data

    def clean_slug(self):
        slug = slugify(self.cleaned_data['slug'])

        if not slug:
            raise ValidationError(_("Slug must not be empty."))
        return slug
Ejemplo n.º 35
0
class AdvancedSettingsForm(forms.ModelForm):
    from cms.forms.fields import PageSmartLinkField
    application_urls = forms.ChoiceField(
        label=_('Application'),
        choices=(),
        required=False,
        help_text=_('Hook application to this page.'))
    overwrite_url = forms.CharField(
        label=_('Overwrite URL'),
        max_length=255,
        required=False,
        help_text=_('Keep this field empty if standard path should be used.'))

    xframe_options = forms.ChoiceField(
        choices=Page._meta.get_field('xframe_options').choices,
        label=_('X Frame Options'),
        help_text=_(
            'Whether this page can be embedded in other pages or websites'),
        initial=Page._meta.get_field('xframe_options').default,
        required=False)

    redirect = PageSmartLinkField(
        label=_('Redirect'),
        required=False,
        help_text=_('Redirects to this URL.'),
        placeholder_text=_('Start typing...'),
        ajax_view='admin:cms_page_get_published_pagelist')

    language = forms.ChoiceField(
        label=_("Language"),
        choices=get_language_tuple(),
        help_text=_('The current language of the content fields.'))

    # This is really a 'fake' field which does not correspond to any Page attribute
    # But creates a stub field to be populate by js
    application_configs = forms.ChoiceField(
        label=_('Application configurations'),
        choices=(),
        required=False,
    )
    fieldsets = ((None, {
        'fields': ('overwrite_url', 'redirect'),
    }), (_('Language independent options'), {
        'fields': (
            'site',
            'template',
            'reverse_id',
            'soft_root',
            'navigation_extenders',
            'application_urls',
            'application_namespace',
            'application_configs',
            'xframe_options',
        )
    }))

    def __init__(self, *args, **kwargs):
        super(AdvancedSettingsForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'navigation_extenders' in self.fields:
            navigation_extenders = self.get_navigation_extenders()
            self.fields['navigation_extenders'].widget = forms.Select(
                {}, [('', "---------")] + navigation_extenders)
        if 'application_urls' in self.fields:
            # Prepare a dict mapping the apps by class name ('PollApp') to
            # their app_name attribute ('polls'), if any.
            app_namespaces = {}
            app_configs = {}
            for hook in apphook_pool.get_apphooks():
                app = apphook_pool.get_apphook(hook[0])
                if app.app_name:
                    app_namespaces[hook[0]] = app.app_name
                if app.app_config:
                    app_configs[hook[0]] = app

            self.fields['application_urls'].widget = AppHookSelect(
                attrs={'id': 'application_urls'},
                app_namespaces=app_namespaces)
            self.fields['application_urls'].choices = [
                ('', "---------")
            ] + apphook_pool.get_apphooks()

            page_data = self.data if self.data else self.initial
            if app_configs:
                self.fields[
                    'application_configs'].widget = ApplicationConfigSelect(
                        attrs={'id': 'application_configs'},
                        app_configs=app_configs)

                if page_data.get(
                        'application_urls', False
                ) and page_data['application_urls'] in app_configs:
                    self.fields['application_configs'].choices = [
                        (config.pk, force_text(config))
                        for config in app_configs[
                            page_data['application_urls']].get_configs()
                    ]

                    apphook = page_data.get('application_urls', False)
                    try:
                        config = apphook_pool.get_apphook(apphook).get_configs(
                        ).get(namespace=self.initial['application_namespace'])
                        self.fields['application_configs'].initial = config.pk
                    except ObjectDoesNotExist:
                        # Provided apphook configuration doesn't exist (anymore),
                        # just skip it
                        # The user will choose another value anyway
                        pass
                else:
                    # If app_config apphook is not selected, drop any value
                    # for application_configs to avoid the field data from
                    # being validated by the field itself
                    try:
                        del self.data['application_configs']
                    except KeyError:
                        pass

        if 'redirect' in self.fields:
            self.fields['redirect'].widget.language = self.fields[
                'language'].initial

    def get_navigation_extenders(self):
        return menu_pool.get_menus_by_attribute("cms_enabled", True)

    def _check_unique_namespace_instance(self, namespace):
        return Page.objects.filter(publisher_is_draft=True,
                                   application_namespace=namespace).exclude(
                                       pk=self.instance.pk).exists()

    def clean(self):
        cleaned_data = super(AdvancedSettingsForm, self).clean()

        if self._errors:
            # Fail fast if there's errors in the form
            return cleaned_data

        language = cleaned_data['language']
        # Language has been validated already
        # so we know it exists.
        language_name = get_language_object(
            language, site_id=cleaned_data['site'].pk)['name']

        try:
            title = self.instance.title_set.get(language=language)
        except Title.DoesNotExist:
            # This covers all cases where users try to edit
            # page advanced settings without creating the page title.
            message = _("Please create the %(language)s page "
                        "translation before editing its advanced settings.")
            raise ValidationError(message % {'language': language_name})

        if not title.slug:
            # This covers all cases where users try to edit
            # page advanced settings without setting a title slug
            # for page titles that already exist.
            message = _("Please set the %(language)s slug "
                        "before editing its advanced settings.")
            raise ValidationError(message % {'language': language_name})

        if 'reverse_id' in self.fields:
            id = cleaned_data['reverse_id']
            site_id = cleaned_data['site']
            if id:
                if Page.objects.filter(reverse_id=id,
                                       site=site_id,
                                       publisher_is_draft=True).exclude(
                                           pk=self.instance.pk).exists():
                    self._errors['reverse_id'] = self.error_class(
                        [_('A page with this reverse URL id exists already.')])
        apphook = cleaned_data.get('application_urls', None)
        # The field 'application_namespace' is a misnomer. It should be
        # 'instance_namespace'.
        instance_namespace = cleaned_data.get('application_namespace', None)
        application_config = cleaned_data.get('application_configs', None)
        if apphook:
            # application_config wins over application_namespace
            if application_config:
                # the value of the application config namespace is saved in
                # the 'usual' namespace field to be backward compatible
                # with existing apphooks
                config = apphook_pool.get_apphook(apphook).get_configs().get(
                    pk=int(application_config))
                if self._check_unique_namespace_instance(config.namespace):
                    # Looks like there's already one with the default instance
                    # namespace defined.
                    self._errors['application_configs'] = ErrorList([
                        _('An application instance using this configuration already exists.'
                          )
                    ])
                else:
                    self.cleaned_data[
                        'application_namespace'] = config.namespace
            else:
                if instance_namespace:
                    if self._check_unique_namespace_instance(
                            instance_namespace):
                        self._errors['application_namespace'] = ErrorList([
                            _('An application instance with this name already exists.'
                              )
                        ])
                else:
                    # The attribute on the apps 'app_name' is a misnomer, it should be
                    # 'application_namespace'.
                    application_namespace = apphook_pool.get_apphook(
                        apphook).app_name
                    if application_namespace and not instance_namespace:
                        if self._check_unique_namespace_instance(
                                application_namespace):
                            # Looks like there's already one with the default instance
                            # namespace defined.
                            self._errors['application_namespace'] = ErrorList([
                                _('An application instance with this name already exists.'
                                  )
                            ])
                        else:
                            # OK, there are zero instances of THIS app that use the
                            # default instance namespace, so, since the user didn't
                            # provide one, we'll use the default. NOTE: The following
                            # line is really setting the "instance namespace" of the
                            # new app to the app’s "application namespace", which is
                            # the default instance namespace.
                            self.cleaned_data[
                                'application_namespace'] = application_namespace

        if instance_namespace and not apphook:
            self.cleaned_data['application_namespace'] = None

        if application_config and not apphook:
            self.cleaned_data['application_configs'] = None

        return self.cleaned_data

    def clean_xframe_options(self):
        if 'xframe_options' not in self.fields:
            return  # nothing to do, field isn't present

        xframe_options = self.cleaned_data['xframe_options']
        if xframe_options == '':
            return Page._meta.get_field('xframe_options').default

        return xframe_options

    def clean_overwrite_url(self):
        if 'overwrite_url' in self.fields:
            url = self.cleaned_data['overwrite_url']
            is_valid_url(url, self.instance)
            return url

    class Meta:
        model = Page
        fields = [
            'site',
            'template',
            'reverse_id',
            'overwrite_url',
            'redirect',
            'soft_root',
            'navigation_extenders',
            'application_urls',
            'application_namespace',
            "xframe_options",
        ]
Ejemplo n.º 36
0
    def __init__(self, *args, **kwargs):
        super(AdvancedSettingsForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'navigation_extenders' in self.fields:
            navigation_extenders = self.get_navigation_extenders()
            self.fields['navigation_extenders'].widget = forms.Select(
                {}, [('', "---------")] + navigation_extenders)
        if 'application_urls' in self.fields:
            # Prepare a dict mapping the apps by class name ('PollApp') to
            # their app_name attribute ('polls'), if any.
            app_namespaces = {}
            app_configs = {}
            for hook in apphook_pool.get_apphooks():
                app = apphook_pool.get_apphook(hook[0])
                if app.app_name:
                    app_namespaces[hook[0]] = app.app_name
                if app.app_config:
                    app_configs[hook[0]] = app

            self.fields['application_urls'].widget = AppHookSelect(
                attrs={'id': 'application_urls'},
                app_namespaces=app_namespaces)
            self.fields['application_urls'].choices = [
                ('', "---------")
            ] + apphook_pool.get_apphooks()

            page_data = self.data if self.data else self.initial
            if app_configs:
                self.fields[
                    'application_configs'].widget = ApplicationConfigSelect(
                        attrs={'id': 'application_configs'},
                        app_configs=app_configs)

                if page_data.get(
                        'application_urls', False
                ) and page_data['application_urls'] in app_configs:
                    self.fields['application_configs'].choices = [
                        (config.pk, force_text(config))
                        for config in app_configs[
                            page_data['application_urls']].get_configs()
                    ]

                    apphook = page_data.get('application_urls', False)
                    try:
                        config = apphook_pool.get_apphook(apphook).get_configs(
                        ).get(namespace=self.initial['application_namespace'])
                        self.fields['application_configs'].initial = config.pk
                    except ObjectDoesNotExist:
                        # Provided apphook configuration doesn't exist (anymore),
                        # just skip it
                        # The user will choose another value anyway
                        pass
                else:
                    # If app_config apphook is not selected, drop any value
                    # for application_configs to avoid the field data from
                    # being validated by the field itself
                    try:
                        del self.data['application_configs']
                    except KeyError:
                        pass

        if 'redirect' in self.fields:
            self.fields['redirect'].widget.language = self.fields[
                'language'].initial
Ejemplo n.º 37
0
    def populate(self):
        self.page = get_page_draft(self.request.current_page)
        user = getattr(self.request, 'user', None)
        try:
            view_name = self.request.resolver_match.view_name
        except AttributeError:
            view_name = None

        if user and view_name:
            obj = None
            language = get_language_from_request(self.request, check_path=True)
            group = person = None
            if view_name == '%s:group-detail' % DEFAULT_APP_NAMESPACE:
                if ALDRYN_PEOPLE_HIDE_GROUPS == 0:
                    group = get_obj_from_request(Group, self.request)
            elif view_name in [
                    '%s:person-detail' % DEFAULT_APP_NAMESPACE,
                    '%s:download_vcard' % DEFAULT_APP_NAMESPACE
            ]:
                obj = get_obj_from_request(Person, self.request)
                if obj and obj.groups:
                    group = obj.primary_group
            elif view_name == '%s:group-list' % DEFAULT_APP_NAMESPACE:
                pass
            else:
                # We don't appear to be on any aldryn_people views so this
                # menu shouldn't even be here.
                return

            menu = self.toolbar.get_or_create_menu('people-app', "People")

            change_group_perm = user.has_perm('aldryn_people.change_group')
            add_group_perm = user.has_perm('aldryn_people.add_group')
            group_perms = [change_group_perm, add_group_perm]

            change_person_perm = user.has_perm('aldryn_people.change_person')
            add_person_perm = user.has_perm('aldryn_people.add_person')
            person_perms = [change_person_perm, add_person_perm]

            if ALDRYN_PEOPLE_HIDE_GROUPS == 0:
                if change_group_perm:
                    url = admin_reverse('aldryn_people_group_changelist')
                    menu.add_sideframe_item(_('Group list'), url=url)

                if add_group_perm:
                    url_args = {}
                    if language:
                        url_args.update({"language": language})
                    url = get_admin_url('aldryn_people_group_add', **url_args)
                    menu.add_modal_item(_('Add new group'), url=url)

                if change_group_perm and group:
                    url = get_admin_url('aldryn_people_group_change', [
                        group.pk,
                    ])
                    menu.add_modal_item(_('Edit group'), url=url, active=True)

                if any(group_perms) and any(person_perms):
                    menu.add_break()

            if change_person_perm:
                url = admin_reverse('aldryn_people_person_changelist')
                menu.add_sideframe_item(_('Person list'), url=url)

            if add_person_perm:
                url_args = {}
                if group:
                    url_args['groups'] = group.pk
                if language:
                    url_args['language'] = language
                url = get_admin_url('aldryn_people_person_add', **url_args)
                menu.add_modal_item(_('Add new person'), url=url)

            if change_person_perm and obj:
                url = admin_reverse('aldryn_people_person_change',
                                    args=(obj.pk, ))
                menu.add_modal_item(_('Edit person'), url=url, active=True)

            if settings.USE_I18N:  # and not self._language_menu:
                if obj:
                    self._language_menu = self.toolbar.get_or_create_menu(
                        LANGUAGE_MENU_IDENTIFIER, _('Language'), position=-1)
                    self._language_menu.items = []
                    languages = get_language_dict(self.current_site.pk)
                    page_languages = self.page.get_languages()
                    remove = []

                    for code, name in get_language_tuple():
                        if code in obj.get_available_languages():
                            remove.append((code, name))
                            try:
                                url = obj.get_absolute_url(code)
                            except NoReverseMatch:
                                url = None
                            if url and code in page_languages:
                                self._language_menu.add_link_item(
                                    name,
                                    url=url,
                                    active=self.current_lang == code)

                    if self.toolbar.edit_mode_active:
                        add = [l for l in languages.items() if l not in remove]
                        copy = [
                            (code, name) for code, name in languages.items()
                            if code != self.current_lang and (code,
                                                              name) in remove
                        ]

                        if (add or len(remove) > 1
                                or copy) and change_person_perm:
                            self._language_menu.add_break(
                                ADD_OBJ_LANGUAGE_BREAK)

                            if add:
                                add_plugins_menu = self._language_menu.get_or_create_menu(
                                    '{0}-add-trans'.format(
                                        LANGUAGE_MENU_IDENTIFIER),
                                    _('Add Translation'))
                                for code, name in add:
                                    url_args = {}
                                    url = '%s?language=%s' % (get_admin_url(
                                        'aldryn_people_person_change',
                                        [obj.pk], **url_args), code)
                                    add_plugins_menu.add_modal_item(name,
                                                                    url=url)

                            if len(remove) > 1:
                                remove_plugins_menu = self._language_menu.get_or_create_menu(
                                    '{0}-del-trans'.format(
                                        LANGUAGE_MENU_IDENTIFIER),
                                    _('Delete Translation'))
                                for code, name in remove:
                                    url = get_admin_url(
                                        'aldryn_people_person_delete_translation',
                                        [obj.pk, code])
                                    remove_plugins_menu.add_modal_item(name,
                                                                       url=url)

                            if copy:
                                copy_plugins_menu = self._language_menu.get_or_create_menu(
                                    '{0}-copy-trans'.format(
                                        LANGUAGE_MENU_IDENTIFIER),
                                    _('Copy all plugins'))
                                title = _('from %s')
                                question = _(
                                    'Are you sure you want to copy all plugins from %s?'
                                )
                                url = get_admin_url(
                                    'aldryn_people_person_copy_language',
                                    [obj.pk])
                                for code, name in copy:
                                    copy_plugins_menu.add_ajax_item(
                                        title % name,
                                        action=url,
                                        data={
                                            'source_language': code,
                                            'target_language':
                                            self.current_lang
                                        },
                                        question=question % name,
                                        on_success=self.toolbar.REFRESH_PAGE)
Ejemplo n.º 38
0
class AdvancedSettingsForm(forms.ModelForm):
    from cms.forms.fields import PageSmartLinkField
    application_urls = forms.ChoiceField(label=_('Application'),
                                         choices=(), required=False,
                                         help_text=_('Hook application to this page.'))
    overwrite_url = forms.CharField(label=_('Overwrite URL'), max_length=255, required=False,
                                    help_text=_('Keep this field empty if standard path should be used.'))

    xframe_options = forms.ChoiceField(
        choices=Page._meta.get_field('xframe_options').choices,
        label=_('X Frame Options'),
        help_text=_('Whether this page can be embedded in other pages or websites'),
        initial=Page._meta.get_field('xframe_options').default,
        required=False
    )

    redirect = PageSmartLinkField(label=_('Redirect'), required=False,
                    help_text=_('Redirects to this URL.'), placeholder_text=_('Start typing...'),
                    ajax_view='admin:cms_page_get_published_pagelist'
    )

    language = forms.ChoiceField(label=_("Language"), choices=get_language_tuple(),
                                 help_text=_('The current language of the content fields.'))

    fieldsets = (
        (None, {
            'fields': ('overwrite_url','redirect'),
        }),
        ('Language independent options', {
            'fields': ('site', 'template', 'reverse_id', 'soft_root', 'navigation_extenders',
            'application_urls', 'application_namespace', "xframe_options",)
        })
    )

    def __init__(self, *args, **kwargs):
        super(AdvancedSettingsForm, self).__init__(*args, **kwargs)
        self.fields['language'].widget = HiddenInput()
        self.fields['site'].widget = HiddenInput()
        site_id = self.fields['site'].initial

        languages = get_language_tuple(site_id)
        self.fields['language'].choices = languages
        if not self.fields['language'].initial:
            self.fields['language'].initial = get_language()
        if 'navigation_extenders' in self.fields:
            self.fields['navigation_extenders'].widget = forms.Select({},
                [('', "---------")] + menu_pool.get_menus_by_attribute("cms_enabled", True))
        if 'application_urls' in self.fields:
            # Prepare a dict mapping the apps by class name ('PollApp') to
            # their app_name attribute ('polls'), if any.
            app_namespaces = {}
            for hook in apphook_pool.get_apphooks():
                app = apphook_pool.get_apphook(hook[0])
                if app.app_name:
                    app_namespaces[hook[0]] = app.app_name

            self.fields['application_urls'].widget = AppHookSelect(
                attrs={'id':'application_urls'},
                app_namespaces=app_namespaces,
            )
            self.fields['application_urls'].choices = [('', "---------")] + apphook_pool.get_apphooks()

        if 'redirect' in self.fields:
            self.fields['redirect'].widget.language = self.fields['language'].initial

    def clean(self):
        cleaned_data = super(AdvancedSettingsForm, self).clean()
        if 'reverse_id' in self.fields:
            id = cleaned_data['reverse_id']
            site_id = cleaned_data['site']
            if id:
                if Page.objects.filter(reverse_id=id, site=site_id, publisher_is_draft=True).exclude(
                        pk=self.instance.pk).count():
                    self._errors['reverse_id'] = self.error_class(
                        [_('A page with this reverse URL id exists already.')])
        apphook = cleaned_data.get('application_urls', None)
        # The field 'application_namespace' is a misnomer. It should be
        # 'instance_namespace'.
        instance_namespace = cleaned_data.get('application_namespace', None)
        if apphook:
            # The attribute on the apps 'app_name' is a misnomer, it should be
            # 'application_namespace'.
            application_namespace = apphook_pool.get_apphook(apphook).app_name
            if application_namespace and not instance_namespace:
                if Page.objects.filter(
                    publisher_is_draft=True,
                    application_urls=apphook,
                    application_namespace=application_namespace
                ).exclude(pk=self.instance.pk).count():
                    # Looks like there's already one with the default instance
                    # namespace defined.
                    self._errors['application_urls'] = ErrorList([
                        _('''You selected an apphook with an "app_name".
                            You must enter a unique instance name.''')
                    ])
                else:
                    # OK, there are zero instances of THIS app that use the
                    # default instance namespace, so, since the user didn't
                    # provide one, we'll use the default. NOTE: The following
                    # line is really setting the "instance namespace" of the
                    # new app to the app’s "application namespace", which is
                    # the default instance namespace.
                    self.cleaned_data['application_namespace'] = application_namespace

        if instance_namespace and not apphook:
            self.cleaned_data['application_namespace'] = None

        return cleaned_data

    def clean_application_namespace(self):
        namespace = self.cleaned_data['application_namespace']
        if namespace and Page.objects.filter(publisher_is_draft=True, application_namespace=namespace).exclude(pk=self.instance.pk).count():
            raise ValidationError(_('A instance name with this name already exists.'))
        return namespace

    def clean_xframe_options(self):
        if 'xframe_options' not in self.fields:
            return # nothing to do, field isn't present

        xframe_options = self.cleaned_data['xframe_options']
        if xframe_options == '':
            return Page._meta.get_field('xframe_options').default

        return xframe_options

    def clean_overwrite_url(self):
        if 'overwrite_url' in self.fields:
            url = self.cleaned_data['overwrite_url']
            is_valid_url(url, self.instance)
            return url

    class Meta:
        model = Page
        fields = [
            'site', 'template', 'reverse_id', 'overwrite_url', 'redirect', 'soft_root', 'navigation_extenders',
            'application_urls', 'application_namespace', "xframe_options",
        ]