Esempio n. 1
0
    def render(self, context):
        if not 'request' in context:
            return ''
        request = context['request']
        width_var = getattr(self, 'width_var', None)
        if width_var:
            try:
                width = int(width_var.resolve(context))
                context.update({'width': width})
            except (template.VariableDoesNotExist, ValueError):
                pass

        page = request.current_page
        if not page or page == "dummy":
            return ""
        
        try:
            placeholder = page.placeholders.get(slot=self.name)
        except Placeholder.DoesNotExist:
            from cms.utils.plugins import get_placeholders
            placeholders = get_placeholders(selected_template)
            found = None
            for slot in placeholders:
                new, created = page.placeholders.get_or_create(slot=slot)
                if slot == self.name:
                    found = new
            placeholder = found
        content = self.get_content(request, page, context)
        if not content:
            if self.nodelist_or:
                content = self.nodelist_or.render(context)
            if self.edit_mode(placeholder, context):
                return render_placeholder_toolbar(placeholder, context, content)
            return content
        return content
Esempio n. 2
0
def seek_and_destroy(dryrun=False, debug=True):
    """Find the page placeholders not longer in use and remove them. This is
	useful in situations where you change templates wholesale (v1 -> v2 etc)
	and need to clear out the chaff from the database"""

    # Go though each page, look at the placeholders in the page
    # template and compare to what it currently has.
    for page in Page.objects.all():
        try:
            template_placeholders = get_placeholders(page.get_template())
        except TemplateDoesNotExist:
            if debug:
                print '** "%s" has template "%s" which could not be found **' % (
                    page.get_title(),
                    page.template,
                )

            continue

        if debug:
            print '"%s" has %s placeholder(s):' % (page.get_title(),
                                                   len(template_placeholders))

        for placeholder in page.placeholders.all():
            if not placeholder.slot in template_placeholders:
                if debug:
                    print '   "%s" has "%s" placeholder slot which is no longer in use' % (
                        page.get_title(), placeholder.slot)

                # This placeholder is not welcome here.
                if not dryrun:
                    page.placeholders.remove(placeholder)
Esempio n. 3
0
 def render_toolbar(self, request):
     from cms.plugin_pool import plugin_pool
     from cms.utils.admin import get_admin_menu_item_context
     """
     Renders the Toolbar.
     """
     auth = request.user.is_staff or request.user.is_superuser
     edit = request.session.get('cms_edit', False) and auth
     page = request.current_page
     move_dict = []
     if edit and page:
         template = get_template_from_request(request)
         placeholders = get_placeholders(template)
         for placeholder in placeholders:
             d = {}
             name = cms_settings.CMS_PLACEHOLDER_CONF.get(
                 "%s %s" % (page.get_template(), placeholder),
                 {}).get("name", None)
             if not name:
                 name = cms_settings.CMS_PLACEHOLDER_CONF.get(
                     placeholder, {}).get("name", None)
             if not name:
                 name = title(placeholder)
             else:
                 name = _(name)
             d['name'] = name
             plugins = plugin_pool.get_all_plugins(placeholder, page)
             d['plugins'] = []
             for p in plugins:
                 d['plugins'].append(p.value)
             d['type'] = placeholder
             move_dict.append(d)
         data = safe(simplejson.dumps(move_dict))
     else:
         data = {}
     if auth and page:
         context = get_admin_menu_item_context(request,
                                               page,
                                               filtered=False)
     else:
         context = {}
     context.update({
         'auth': auth,
         'page': page,
         'templates': cms_settings.CMS_TEMPLATES,
         'auth_error': not auth and 'cms_username' in request.POST,
         'placeholder_data': data,
         'edit': edit,
         'moderator': cms_settings.CMS_MODERATOR,
         'CMS_MEDIA_URL': cms_settings.CMS_MEDIA_URL,
     })
     #from django.core.context_processors import csrf
     #context.update(csrf(request))
     return render_to_string('cms/toolbar/toolbar.html', context,
                             RequestContext(request))
Esempio n. 4
0
def update_placeholders(instance, **kwargs):
    from cms.utils.plugins import get_placeholders
    placeholders = get_placeholders(instance.get_template())
    found = {}
    for placeholder in instance.placeholders.all():
        if placeholder.slot in placeholders:
            found[placeholder.slot] = placeholder
    for placeholder_name in placeholders:
        if not placeholder_name in found:
            placeholder = Placeholder.objects.create(slot=placeholder_name)
            instance.placeholders.add(placeholder)
            found[placeholder_name] = placeholder
Esempio n. 5
0
def get_plugins_for_page(request, page, lang=None):
    from cms.utils.plugins import get_placeholders

    if not page:
        return []
    lang = lang or get_language_from_request(request)
    if not hasattr(page, '_%s_plugins_cache' % lang):
        slots = get_placeholders(page.template)
        setattr(page, '_%s_plugins_cache' % lang, get_cmsplugin_queryset(request).filter(
            placeholder__page=page, placeholder__slot__in=slots, language=lang, parent__isnull=True
        ).order_by('placeholder', 'position').select_related())
    return getattr(page, '_%s_plugins_cache' % lang)
Esempio n. 6
0
def _get_placeholder(current_page, page, context, name):
    from cms.utils.plugins import get_placeholders
    placeholder_cache = getattr(current_page, '_tmp_placeholders_cache', {})
    if page.pk in placeholder_cache:
        return placeholder_cache[page.pk].get(name, None)
    placeholder_cache[page.pk] = {}
    slots = get_placeholders(page.get_template())
    placeholders = page.placeholders.filter(slot__in=slots)
    assign_plugins(context['request'], placeholders, get_language())
    for placeholder in placeholders:
        placeholder_cache[page.pk][placeholder.slot] = placeholder
        placeholder.page = page
    current_page._tmp_placeholders_cache = placeholder_cache
    return placeholder_cache[page.pk].get(name, None)
Esempio n. 7
0
def _get_placeholder(current_page, page, context, name):
    from cms.utils.plugins import get_placeholders
    placeholder_cache = getattr(current_page, '_tmp_placeholders_cache', {})
    if page.pk in placeholder_cache:
        return placeholder_cache[page.pk].get(name, None)
    placeholder_cache[page.pk] = {}
    slots = get_placeholders(page.get_template())
    placeholders = page.placeholders.filter(slot__in=slots)
    assign_plugins(context['request'], placeholders, get_language())
    for placeholder in placeholders:
        placeholder_cache[page.pk][placeholder.slot] = placeholder
        placeholder.page = page
    current_page._tmp_placeholders_cache = placeholder_cache
    return placeholder_cache[page.pk].get(name, None)
Esempio n. 8
0
 def render_toolbar(self, request):
     from cms.plugin_pool import plugin_pool
     from cms.utils.admin import get_admin_menu_item_context
     """
     Renders the Toolbar.
     """
     auth = request.user.is_staff or request.user.is_superuser
     edit = request.session.get('cms_edit', False) and auth
     page = request.current_page
     move_dict = []
     if edit and page:
         template = get_template_from_request(request)
         placeholders = get_placeholders(template)
         for placeholder in placeholders:
             d = {}
             name = cms_settings.CMS_PLACEHOLDER_CONF.get("%s %s" % (page.get_template(), placeholder), {}).get("name", None)
             if not name:
                 name = cms_settings.CMS_PLACEHOLDER_CONF.get(placeholder, {}).get("name", None)
             if not name:
                 name = title(placeholder)
             else:
                 name = _(name)
             d['name'] = name
             plugins = plugin_pool.get_all_plugins(placeholder, page)
             d['plugins'] = []
             for p in plugins:
                 d['plugins'].append(p.value)
             d['type'] = placeholder
             move_dict.append(d)
         data = safe(simplejson.dumps(move_dict))
     else:
         data = {}
     if auth and page:
         context = get_admin_menu_item_context(request, page, filtered=False)
     else:
         context = {}
     context.update({
         'auth':auth,
         'page':page,
         'templates': cms_settings.CMS_TEMPLATES,
         'auth_error':not auth and 'cms_username' in request.POST,
         'placeholder_data':data,
         'edit':edit,
         'moderator': cms_settings.CMS_MODERATOR,
         'CMS_MEDIA_URL': cms_settings.CMS_MEDIA_URL,
     })
     #from django.core.context_processors import csrf
     #context.update(csrf(request))
     return render_to_string('cms/toolbar/toolbar.html', context, RequestContext(request))
Esempio n. 9
0
 def get_content(self, request, page, context):
     from cms.utils.plugins import get_placeholders
     pages = [page]
     if self.inherit:
         pages = chain([page], page.get_cached_ancestors(ascending=True))
     for page in pages:
         template = get_template_from_request(request, page)
         placeholder = page.placeholders.filter(slot__in=get_placeholders(template)).get(slot=self.name)
         if not get_plugins(request, placeholder):
             continue
         request.placeholder_media += placeholder.get_media(request, context)
         content = render_placeholder(placeholder, context)
         if content:
             return content
     return ''
Esempio n. 10
0
 def rescan_placeholders(self):
     """
     Rescan and if necessary create placeholders in the current template.
     """
     # inline import to prevent circular imports
     from cms.utils.plugins import get_placeholders
     placeholders = get_placeholders(self.get_template())
     found = {}
     for placeholder in self.placeholders.all():
         if placeholder.slot in placeholders:
             found[placeholder.slot] = placeholder
     for placeholder_name in placeholders:
         if not placeholder_name in found:
             placeholder = Placeholder.objects.create(slot=placeholder_name)
             self.placeholders.add(placeholder)
             found[placeholder_name] = placeholder
 def rescan_placeholders(self):
     """
     Rescan and if necessary create placeholders in the current template.
     """
     # inline import to prevent circular imports
     from cms.utils.plugins import get_placeholders
     placeholders = get_placeholders(self.get_template())
     found = {}
     for placeholder in self.placeholders.all():
         if placeholder.slot in placeholders:
             found[placeholder.slot] = placeholder
     for placeholder_name in placeholders:
         if not placeholder_name in found:
             placeholder = Placeholder.objects.create(slot=placeholder_name)
             self.placeholders.add(placeholder)
             found[placeholder_name] = placeholder
Esempio n. 12
0
    def move_plugin(self, request):
        if 'history' in request.path:
            return HttpResponseBadRequest("Cannot move plugins in history view")

        # Moving a plugin to a new slot
        if 'plugin_id' in request.POST:
            plugin = CMSPlugin.objects.select_related(
                    'placeholder').get(pk=int(request.POST['plugin_id']))
            slot = request.POST['placeholder']

            item = NewsItem.objects.get(placeholders=plugin.placeholder)

            if slot not in get_placeholders(item.template):
                return HttpResponseBadRequest("Invalid target placeholder")

            placeholder = item.placeholders.get(slot=slot)

            plugin.placeholder = placeholder
            plugin.position = CMSPlugin.objects.filter(
                    placeholder=placeholder).count()
            plugin.parent = None
            plugin.save()

            for descendant in plugin.get_descendants():
                descendant.placeholder = placeholder
                descendant.save()

        # Reordering plugins in a slot
        if 'ids' in request.POST:
            plugin_ids = request.POST['ids'].split("_")
            item = None
            for position in range(0, len(plugin_ids)):
                plugin = CMSPlugin.objects.select_related(
                        'placeholder').get(pk=int(plugin_ids[position]))
                if item is None:
                    item = NewsItem.objects.get(
                            placeholders=plugin.placeholder)
                if plugin.position != position:
                    plugin.position = position
                    plugin.save()

        if item and _REVERSION:
            make_revision_with_plugins(item, request.user,
                "Plugins where moved")

        return HttpResponse(str("ok"))
Esempio n. 13
0
def get_plugins_for_page(request, page, lang=None):
    from cms.utils.plugins import get_placeholders

    if not page:
        return []
    lang = lang or get_language_from_request(request)
    if not hasattr(page, '_%s_plugins_cache' % lang):
        slots = get_placeholders(page.template)
        setattr(
            page, '_%s_plugins_cache' % lang,
            get_cmsplugin_queryset(request).filter(
                placeholder__page=page,
                placeholder__slot__in=slots,
                language=lang,
                parent__isnull=True).order_by('placeholder',
                                              'position').select_related())
    return getattr(page, '_%s_plugins_cache' % lang)
 def forwards(self, orm):
     "Write your forwards methods here."
     from cms.utils.plugins import get_placeholders
     for page in orm.Page.objects.all():
         placeholder_cache = {}
         placeholders = get_placeholders(get_template(page))
         for plugin in orm.CMSPlugin.objects.filter(page=page):
             if plugin.placeholder not in placeholder_cache:
                 placeholder = orm.Placeholder.objects.create(slot=plugin.placeholder)
                 page.placeholders.add(placeholder)
                 placeholder_cache[plugin.placeholder] = placeholder
             plugin.new_placeholder = placeholder_cache[plugin.placeholder]
             plugin.save()
         for placeholder_name in placeholders:
             if placeholder_name not in placeholder_cache:
                 placeholder = orm.Placeholder.objects.create(slot=placeholder_name)
                 page.placeholders.add(placeholder)
Esempio n. 15
0
    def _get_layout_placeholders_fields(self, request, layout):
        formfields = {}
        lang = get_language_from_request(request, layout.from_page)
        # get placeholder slots from page template
        slots = get_placeholders(layout.from_page.get_template())

        fixed_slots = get_fixed_section_slots(slots)
        for fixed_section_name, fixed_slot_name in fixed_slots.items():
            formfield = self._get_fixed_slot_formfield(fixed_section_name)
            formfields[fixed_slot_name] = formfield

        for slot in filter(lambda s: s not in formfields, slots):
            layout_placeholder = layout.get_or_create_placeholder(slot)
            formfield = self._get_slot_formfield(layout_placeholder, lang)
            formfields[slot] = formfield

        return formfields
Esempio n. 16
0
    def move_plugin(self, request):
        if request.method == "POST" and not 'history' in request.path:
            pos = 0
            page = None
            success = False
            if 'plugin_id' in request.POST:
                plugin = CMSPlugin.objects.get(pk=int(request.POST['plugin_id']))
                old_placeholder = plugin.placeholder
                page = get_item_from_placeholder_if_exists(old_placeholder)
                placeholder_slot = request.POST['placeholder']
                placeholders = get_placeholders(page.get_template())
                if not placeholder_slot in placeholders:
                    return HttpResponse(str("error"))
                placeholder = page.placeholders.get(slot=placeholder_slot)
                plugin.placeholder = placeholder
                # plugin positions are 0 based, so just using count here should give us 'last_position + 1'
                position = CMSPlugin.objects.filter(placeholder=placeholder).count()
                plugin.position = position
                plugin.save()
                success = True
            if 'ids' in request.POST:
                for plugin_id in request.POST['ids'].split("_"):
                    plugin = CMSPlugin.objects.get(pk=plugin_id)
                    page = get_item_from_placeholder_if_exists(plugin.placeholder)

                    if page and not page.has_change_permission(request):
                        raise Http404

                    if plugin.position != pos:
                        plugin.position = pos
                        plugin.save()
                    pos += 1
                success = True
            if not success:
                HttpResponse(str("error"))
                
            if page and 'reversion' in settings.INSTALLED_APPS:
                make_revision_with_plugins(page)
                reversion.revision.user = request.user
                reversion.revision.comment = unicode(_(u"Plugins where moved"))
                
            return HttpResponse(str("ok"))
        else:
            return HttpResponse(str("error"))
 def forwards(self, orm):
     "Write your forwards methods here."
     from cms.utils.plugins import get_placeholders
     for page in orm.Page.objects.all():
         placeholder_cache = {}
         placeholders = get_placeholders(get_template(page))
         for plugin in orm.CMSPlugin.objects.filter(page=page):
             if plugin.placeholder not in placeholder_cache:
                 placeholder = orm.Placeholder.objects.create(
                     slot=plugin.placeholder)
                 page.placeholders.add(placeholder)
                 placeholder_cache[plugin.placeholder] = placeholder
             plugin.new_placeholder = placeholder_cache[plugin.placeholder]
             plugin.save()
         for placeholder_name in placeholders:
             if placeholder_name not in placeholder_cache:
                 placeholder = orm.Placeholder.objects.create(
                     slot=placeholder_name)
                 page.placeholders.add(placeholder)
Esempio n. 18
0
def check_placeholders():
    # Go though each page, look at the placeholders in the page
    # template and compare to what it currently has.
    for page in sorted(Page.objects.all(), key=lambda x:x.get_title()):
	try:
	    template_placeholders = map(lambda x:x.slot, get_placeholders(page.get_template()))
	except TemplateDoesNotExist:
	    print '** "%s" has template "%s" which could not be found **' % (
		page.get_title(),
		page.template,
	    )
	    continue
	for placeholder in page.placeholders.all():
	    if not placeholder.slot in template_placeholders:
		print '"%s" id %d has "%s" placeholder slot which is no longer in use' % (
		    page.get_title(),
                    page.id,
		    placeholder.slot
		)
Esempio n. 19
0
def update_placeholders(instance, **kwargs): 
    from cms.utils.plugins import get_placeholders 
    from django.db.models import Max 
    from django.db import IntegrityError 
    from django.db import transaction 
    placeholders = get_placeholders(instance.get_template()) 
    found = {} 
    for placeholder in instance.placeholders.all(): 
        if placeholder.slot in placeholders: 
            found[placeholder.slot] = placeholder 
    for placeholder_name in placeholders: 
        if not placeholder_name in found: 
            sid = transaction.savepoint() 
            try: 
                placeholder = Placeholder.objects.create(slot=placeholder_name) 
            except IntegrityError: 
                transaction.savepoint_rollback(sid) 
                placeholder = Placeholder.objects.create(id=Placeholder.objects.all().aggregate(Max('id') ) ['id__max'] + 1, slot=placeholder_name) 
            instance.placeholders.add(placeholder) 
            found[placeholder_name] = placeholder    
Esempio n. 20
0
def is_valid_for_layout(page, raise_errors=True):
    """
    Checks if a page can be used for a layout
    """
    try:
        slots = get_placeholders(page.get_template())
        slot_finder.get_fixed_section_slots(slots)
    except slot_finder.MissingRequiredPlaceholder as e:
        if not raise_errors:
            return False
        raise ValidationError(
            "Page %s is missing a required placeholder named %s. Add this "
            "placeholder in the page template." % (page, e.slot, ))
    except Exception as page_exception:
        if not raise_errors:
            return False
        raise ValidationError(
            "Error found while scanning template from page %s: %s. "
            "You need to fix this manually." % (page, page_exception))
    return True
Esempio n. 21
0
    def render(self, context):
        if not "request" in context:
            return ""
        request = context["request"]
        width_var = getattr(self, "width_var", None)
        if width_var:
            try:
                width = int(width_var.resolve(context))
                context.update({"width": width})
            except (template.VariableDoesNotExist, ValueError):
                pass

        page = request.current_page
        if not page or page == "dummy":
            return ""

        try:
            placeholder = page.placeholders.get(slot=self.name)
        except Placeholder.DoesNotExist:
            from cms.utils.plugins import get_placeholders

            placeholders = get_placeholders(page.get_template())
            found = None
            for slot in placeholders:
                new, created = page.placeholders.get_or_create(slot=slot)
                if slot == self.name:
                    found = new
            placeholder = found
            if not found:
                if settings.DEBUG:
                    raise Placeholder.DoesNotExist("No placeholder '%s' found for page '%s'" % (self.name, page.pk))
                else:
                    return "<!-- ERROR:cms.utils.plugins.get_placeholders:%s -->" % self.name
        content = self.get_content(request, page, context)
        if not content:
            if self.nodelist_or:
                content = self.nodelist_or.render(context)
            if self.edit_mode(placeholder, context):
                return render_placeholder_toolbar(placeholder, context, content)
            return content
        return content
Esempio n. 22
0
    def get_fieldsets(self, request, obj=None):
        """
        Add fieldsets of placeholders to the list of already existing
        fieldsets.
        """

        if obj: # edit
            fieldsets = deepcopy(self.fieldsets)
            placeholders = get_placeholders(
                    get_template_from_request(request, obj))

            for placeholder in placeholders:
                name = get_placeholder_conf("name", placeholder, obj.template,
                        placeholder)
                name = _(name)
                fieldsets.append((title(name), {'fields': [placeholder],
                    'classes': ['plugin-holder']}))
        else: # new page
            fieldsets = deepcopy(self.add_fieldsets)

        return fieldsets
Esempio n. 23
0
 def change_view(self, request, object_id, extra_context=None):
     """
     The 'change' admin view for the NewsItem model.
     """
     try:
         obj = self.model.objects.get(pk=object_id)
     except (self.model.DoesNotExist, ValueError,):
         # Don't raise Http404 just yet, because we haven't checked
         # permissions yet. We don't want an unauthenticated user to be able
         # to determine whether a given object exists.
         obj = None
     else:
         selected_template = get_template_from_request(request, obj)
         moderation_level, moderation_required = 0, False
         
         # if there is a delete request for this page
         moderation_delete_request = False
         
         #activate(user_lang_set)
         extra_context = {
             'placeholders': get_placeholders(selected_template),
             'page': obj,
             'CMS_PERMISSION': settings.CMS_PERMISSION,
             'CMS_MODERATOR': settings.CMS_MODERATOR,
             'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX,
             'has_change_permissions_permission': True,
             'has_moderate_permission': True,
             'moderation_level': moderation_level,
             'moderation_required': moderation_required,
             'moderator_should_approve': False,
             'moderation_delete_request': moderation_delete_request,
             'show_delete_translation': False,
             'current_site_id': settings.SITE_ID,
             'language': get_language_from_request(request, obj),
             'language_tabs': self._get_site_languages(obj),
             'show_language_tabs': False
         }
     
     return super(NewsItemAdmin, self).change_view(request, object_id, extra_context)
Esempio n. 24
0
    def get_fieldsets(self, request, obj=None):
        """
        Add fieldsets of placeholders to the list of already existing
        fieldsets.
        """
        placeholders_template = get_template_from_request(request, obj)

        if obj: # edit
            given_fieldsets = deepcopy(self.fieldsets)
            for placeholder_name in sorted(get_placeholders(placeholders_template)):
                name = settings.CMS_PLACEHOLDER_CONF.get("%s %s" % (obj.template, placeholder_name), {}).get("name", None)
                if not name:
                    name = settings.CMS_PLACEHOLDER_CONF.get(placeholder_name, {}).get("name", None)
                if not name:
                    name = placeholder_name
                else:
                    name = _(name)
                given_fieldsets += [(title(name), {'fields':[placeholder_name], 'classes':['plugin-holder']})]
        else: # new page
            given_fieldsets = deepcopy(self.add_fieldsets)

        return given_fieldsets
Esempio n. 25
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        """
        The 'change' admin view for the NewsItem model.
        """
        try:
            obj = self.model.objects.get(pk=object_id)
        except (self.model.DoesNotExist, ValueError,):
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None
        else:
            selected_template = get_template_from_request(request, obj)
            extra_context = {
                'placeholders': get_placeholders(selected_template),
                'page': obj,
                'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX,
                'current_site_id': settings.SITE_ID,
                'language': 'en'
            }

        return super(NewsItemAdmin, self).change_view(request, object_id,
                form_url=form_url, extra_context=extra_context)
    def _get_patched_current_page(self):
        """
        Returns the current page required by CMS when rendering plugins.
        Uses django cms placeholder tag rendering logic and sets the cache
        attributes on the current page in order to stop CMS from fetching
        the plugins from the actual page.
        """
        page = self.layout.from_page
        # set placeholders cache
        placeholder_cache = {page.pk: {}, }
        # TODO maybe memoize this func call
        slots = get_placeholders(page.get_template())

        overwritten_slots = {
            phd.slot: phd
            for phd in self.layout.hidden_placeholders.filter(
                slot__in=slots, cmsplugin__isnull=False)}

        # fixed placeholders(header/content)
        fixed_placeholders = self._get_fixed_slots(slots)

        for original_phd in page.placeholders.filter(slot__in=slots):
            slot = original_phd.slot
            placeholder = (fixed_placeholders.get(slot, None) or
                           overwritten_slots.get(slot, None) or
                           original_phd)
            setattr(placeholder, 'page', page)
            self._cache_plugins_for_placeholder(placeholder)
            placeholder_cache[page.pk][slot] = placeholder
        # set the placeholders on the current page before django-cms does.
        # this variable name is used by cms to hold placeholders with all
        #   plugins. By setting this variable before cms, we ensure that cms
        #   will not cache the `real` page placeholders and will use the ones
        #   we set
        setattr(page, '_tmp_placeholders_cache', placeholder_cache)
        return page
Esempio n. 27
0
 def test_placeholder_scanning_super(self):
     placeholders = get_placeholders('placeholder_tests/test_five.html')
     self.assertEqual(sorted(placeholders),
                      sorted([u'one', u'extra_one', u'two', u'three']))
Esempio n. 28
0
 def test_placeholder_scanning_sekizai_double_extend(self):
     placeholders = get_placeholders(
         'placeholder_tests/test_three_sekizai.html')
     self.assertEqual(sorted(placeholders),
                      sorted([u'new_one', u'two', u'new_three']))
Esempio n. 29
0
 def test_placeholder_scanning_complex(self):
     placeholders = get_placeholders('placeholder_tests/test_four.html')
     self.assertEqual(sorted(placeholders),
                      sorted([u'new_one', u'child', u'four']))
Esempio n. 30
0
 def test_placeholder_scanning_nested_super(self):
     placeholders = get_placeholders(
         'placeholder_tests/nested_super_level1.html')
     self.assertEqual(sorted(placeholders),
                      sorted([u'level1', u'level2', u'level3', u'level4']))
Esempio n. 31
0
 def test_placeholder_scanning_include(self):
     placeholders = get_placeholders('placeholder_tests/test_two.html')
     self.assertEqual(sorted(placeholders), sorted([u'child', u'three']))
from cms.models.titlemodels import Title

# https://gist.github.com/nicksnell/9228580 ATTENTION BUG Manque map slot dans template_placeholders
from django.template import TemplateDoesNotExist
from cms.models.pagemodel import Page
from cms.utils.plugins import get_placeholders

phs = Placeholder.objects.all()

for ph in phs:
    if len(ph.get_plugins_list()) > 0:
        continue
    pa = ph.page
    if pa == None:
        continue
    slots = map(lambda x: x.slot, get_placeholders(pa.get_template()))
    if not ph.slot in slots:
        print("deleting " + ph.slot + " from " + pa.get_absolute_url("en"))
        odel = ph.delete()
        if odel[0] != 2 or odel[1]['cms.Placeholder'] != 1 or odel[1][
                'cms.Page_placeholders'] != 1:
            print("OUILLE :")
            print(odel)

phs = Placeholder.objects.filter(slot='equipes')
mama = map(lambda x: len(x.get_plugins_list()), phs)
if len(mama) > 0 and max(mama) == 0:
    print(
        'Removing all "equipes" placeholders, please remove {% placeholder "equipes" %} from templates'
    )
    for ph in phs:
Esempio n. 33
0
 def test_placeholder_scanning_extend_outside_block_nested(self):
     placeholders = get_placeholders("placeholder_tests/outside_nested.html")
     self.assertEqual(sorted(placeholders), sorted([u"new_one", u"two", u"base_outside"]))
Esempio n. 34
0
 def test_placeholder_scanning_complex(self):
     placeholders = get_placeholders('placeholder_tests/test_four.html')
     self.assertEqual(sorted(placeholders), sorted([u'new_one', u'child', u'four']))
Esempio n. 35
0
 def test_placeholder_scanning_super(self):
     placeholders = get_placeholders('placeholder_tests/test_five.html')
     self.assertEqual(sorted(placeholders), sorted([u'one', u'extra_one', u'two', u'three']))
Esempio n. 36
0
 def test_01_placeholder_scanning_extend(self):
     placeholders = get_placeholders('placeholder_tests/test_one.html')
     self.assertEqual(sorted(placeholders),
                      sorted([u'new_one', u'two', u'three']))
Esempio n. 37
0
 def test_placeholder_scanning_sekizai_double_extend(self):
     placeholders = get_placeholders('placeholder_tests/test_three_sekizai.html')
     self.assertEqual(sorted(placeholders), sorted([u'new_one', u'two', u'new_three']))
Esempio n. 38
0
 def test_placeholder_scanning_nested_super(self):
     placeholders = get_placeholders('placeholder_tests/nested_super_level1.html')
     self.assertEqual(sorted(placeholders), sorted([u'level1', u'level2', u'level3', u'level4']))
Esempio n. 39
0
 def test_01_placeholder_scanning_extend(self):
     placeholders = get_placeholders('placeholder_tests/test_one.html')
     self.assertEqual(sorted(placeholders), sorted([u'new_one', u'two', u'three']))
Esempio n. 40
0
 def test_placeholder_scanning_nested(self):
     placeholders = get_placeholders("placeholder_tests/test_six.html")
     self.assertEqual(sorted(placeholders), sorted([u"new_one", u"new_two", u"new_three"]))
Esempio n. 41
0
 def test_placeholder_scanning_nested(self):
     placeholders = get_placeholders('placeholder_tests/test_six.html')
     self.assertEqual(sorted(placeholders),
                      sorted([u'new_one', u'new_two', u'new_three']))
Esempio n. 42
0
 def test_placeholder_scanning_nested(self):
     placeholders = get_placeholders('placeholder_tests/test_six.html')
     self.assertEqual(sorted(placeholders), sorted([u'new_one', u'new_two', u'new_three']))
Esempio n. 43
0
 def test_placeholder_scanning_extend_outside_block(self):
     placeholders = get_placeholders('placeholder_tests/outside.html')
     self.assertEqual(sorted(placeholders),
                      sorted([u'new_one', u'two', u'base_outside']))
Esempio n. 44
0
 def test_placeholder_scanning_sekizai_extend_outside_block_nested(self):
     placeholders = get_placeholders('placeholder_tests/outside_nested_sekizai.html')
     self.assertEqual(sorted(placeholders), sorted([u'new_one', u'two', u'base_outside']))
Esempio n. 45
0
 def test_placeholder_scanning_include(self):
     placeholders = get_placeholders('placeholder_tests/test_two.html')
     self.assertEqual(sorted(placeholders), sorted([u'child', u'three']))
Esempio n. 46
0
 def get_form(self, request, obj=None, **kwargs):
     """
     Get NewsItemForm for the NewsItem model and modify its fields depending 
     on the request.
     """
     if obj:
         form = super(NewsItemAdmin, self).get_form(request, obj, **kwargs)
         version_id = None
         versioned = False
         if "history" in request.path or 'recover' in request.path:
             versioned = True
             version_id = request.path.split("/")[-2]
     else:
         self.inlines = []
         form = NewsItemAddForm
     
     if obj:
         if settings.NEWSY_TEMPLATES:
             selected_template = get_template_from_request(request, obj)
             template_choices = list(settings.NEWSY_TEMPLATES)
             form.base_fields['template'].choices = template_choices
             form.base_fields['template'].initial = force_unicode(selected_template)
         
         placeholders = get_placeholders(selected_template)
         for placeholder_name in placeholders:
             plugin_list = []
             show_copy = False
             if versioned:
                 from reversion.models import Version
                 version = get_object_or_404(Version, pk=version_id)
                 installed_plugins = plugin_pool.get_all_plugins()
                 plugin_list = []
                 plugins = []
                 bases = {}
                 revs = []
                 for related_version in version.revision.version_set.all():
                     try:
                         rev = related_version.object_version
                     except models.FieldDoesNotExist:
                         # in case the model has changed in the meantime
                         continue
                     else:
                         revs.append(rev)
                 for rev in revs:
                     pobj = rev.object
                     if pobj.__class__ == CMSPlugin:
                         if pobj.placeholder.slot == placeholder_name and \
                             not pobj.parent_id:
                             placeholder = pobj.placeholder
                             if pobj.get_plugin_class() == CMSPlugin:
                                 plugin_list.append(pobj)
                             else:
                                 bases[int(pobj.pk)] = pobj
                     if hasattr(pobj, "cmsplugin_ptr_id"):
                         plugins.append(pobj)
                 for plugin in plugins:
                     if int(plugin.cmsplugin_ptr_id) in bases:
                         bases[int(plugin.cmsplugin_ptr_id)].placeholder = placeholder
                         bases[int(plugin.cmsplugin_ptr_id)].set_base_attr(plugin)
                         plugin_list.append(plugin)
             else:
                 placeholder, created = obj.placeholders.get_or_create(slot=placeholder_name)
                 installed_plugins = plugin_pool.get_all_plugins(placeholder_name, obj)
                 plugin_list = CMSPlugin.objects.filter(placeholder=placeholder, parent=None).order_by('position')
             widget = PluginEditor(attrs={
                 'installed': installed_plugins,
                 'list': plugin_list,
                 'copy_languages': [],
                 'show_copy':show_copy,
                 'language': '',
                 'placeholder': placeholder
             })
             form.base_fields[placeholder_name] = CharField(widget=widget, required=False)
     else:
         form.base_fields['template'].initial = settings.NEWSY_TEMPLATES[0][0]
     
     return form