Example #1
0
    def test_dual_legacy_cache_plugins(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        placeholder1 = page1.placeholders.filter(slot="body")[0]
        placeholder2 = page1.placeholders.filter(slot="right-column")[0]
        plugin_pool.register_plugin(LegacyCachePlugin)
        add_plugin(placeholder1, "TextPlugin", 'en', body="English")
        add_plugin(placeholder2, "TextPlugin", 'en', body="Deutsch")
        # Adds a no-cache plugin. In older versions of the CMS, this would
        # prevent the page from caching in, but since this plugin also defines
        # get_cache_expiration() it is ignored.
        add_plugin(placeholder1, "LegacyCachePlugin", 'en')
        # Ensure that we're testing in an environment WITHOUT the MW cache, as
        # we are testing the internal page cache, not the MW cache.
        exclude = [
            'django.middleware.cache.UpdateCacheMiddleware',
            'django.middleware.cache.CacheMiddleware',
            'django.middleware.cache.FetchFromCacheMiddleware',
        ]
        overrides = dict()
        if getattr(settings, 'MIDDLEWARE', None):
            overrides['MIDDLEWARE'] = [mw for mw in settings.MIDDLEWARE if mw not in exclude]
        else:
            overrides['MIDDLEWARE_CLASSES'] = [mw for mw in settings.MIDDLEWARE_CLASSES if mw not in exclude]
        with self.settings(**overrides):
            page1.publish('en')
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(FuzzyInt(14, 25)):
                response = self.client.get('/en/')
            self.assertTrue('no-cache' not in response['Cache-Control'])

        plugin_pool.unregister_plugin(LegacyCachePlugin)
Example #2
0
    def test_moving_plugin_to_different_placeholder(self):
        plugin_pool.register_plugin(DumbFixturePlugin)
        page = create_page("page", "nav_playground.html", "en", published=True)
        plugin_data = {
            'plugin_type': 'DumbFixturePlugin',
            'language': settings.LANGUAGES[0][0],
            'placeholder': page.placeholders.get(slot='body').pk,
        }
        response = self.client.post(URL_CMS_PLUGIN_ADD % page.pk, plugin_data)
        self.assertEquals(response.status_code, 200)

        plugin_data['parent_id'] = int(response.content)
        del plugin_data['placeholder']
        response = self.client.post(URL_CMS_PLUGIN_ADD % page.pk, plugin_data)
        self.assertEquals(response.status_code, 200)

        post = {
            'plugin_id': int(response.content),
            'placeholder': 'right-column',
        }
        response = self.client.post(URL_CMS_PLUGIN_MOVE % page.pk, post)
        self.assertEquals(response.status_code, 200)

        from cms.plugins.utils import build_plugin_tree

        build_plugin_tree(page.placeholders.get(slot='right-column').get_plugins_list())
        plugin_pool.unregister_plugin(DumbFixturePlugin)
Example #3
0
    def setUp(self):
        from django.core.cache import cache
        super(PlaceholderCacheTestCase, self).setUp()
        cache.clear()

        self.page = create_page(
            'en test page', 'nav_playground.html', 'en', published=True)
        # Now create and publish as 'de' title
        create_title('de', "de test page", self.page)
        self.page.publish('de')

        self.placeholder = self.page.placeholders.filter(slot="body")[0]
        plugin_pool.register_plugin(VaryCacheOnPlugin)
        add_plugin(self.placeholder, 'TextPlugin', 'en', body='English')
        add_plugin(self.placeholder, 'TextPlugin', 'de', body='Deutsch')
        add_plugin(self.placeholder, 'VaryCacheOnPlugin', 'en')
        add_plugin(self.placeholder, 'VaryCacheOnPlugin', 'de')

        self.en_request = self.get_request('/en/')
        self.en_request.current_page = Page.objects.get(pk=self.page.pk)

        self.en_us_request = self.get_request('/en/')
        self.en_us_request.META['HTTP_COUNTRY_CODE'] = 'US'

        self.en_uk_request = self.get_request('/en/')
        self.en_uk_request.META['HTTP_COUNTRY_CODE'] = 'UK'

        self.de_request = self.get_request('/de/')
        self.de_request.current_page = Page.objects.get(pk=self.page.pk)
Example #4
0
    def TTLCacheExpirationPlugin(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        placeholder1 = page1.placeholders.filter(slot="body")[0]
        placeholder2 = page1.placeholders.filter(slot="right-column")[0]
        plugin_pool.register_plugin(TTLCacheExpirationPlugin)
        add_plugin(placeholder1, "TextPlugin", 'en', body="English")
        add_plugin(placeholder2, "TextPlugin", 'en', body="Deutsch")

        # Add *CacheExpirationPlugins, one expires in 50s, the other in 40s.
        # The page should expire in the least of these, or 40s.
        add_plugin(placeholder1, "TTLCacheExpirationPlugin", 'en')

        # Ensure that we're testing in an environment WITHOUT the MW cache, as
        # we are testing the internal page cache, not the MW cache.
        exclude = [
            'django.middleware.cache.UpdateCacheMiddleware',
            'django.middleware.cache.CacheMiddleware',
            'django.middleware.cache.FetchFromCacheMiddleware',
        ]
        mw_classes = [mw for mw in settings.MIDDLEWARE_CLASSES if mw not in exclude]

        with self.settings(MIDDLEWARE_CLASSES=mw_classes):
            page1.publish('en')
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(FuzzyInt(14, 25)):  # was 14, 24
                response = self.client.get('/en/')
            self.assertTrue('max-age=50' in response['Cache-Control'], response['Cache-Control'])

            plugin_pool.unregister_plugin(TTLCacheExpirationPlugin)
Example #5
0
 def register_plugin(cls, plugin):
     """
     Register plugins derived from this class with this function instead of
     `plugin_pool.register_plugin`, so that dialog plugins without a corresponding
     form class are not registered.
     """
     if not issubclass(plugin, cls):
         msg = "Can not register plugin class `{}`, since is does not inherit from `{}`."
         raise ImproperlyConfigured(msg.format(plugin.__name__, cls.__name__))
     plugin_pool.register_plugin(plugin)
Example #6
0
    def test_no_cache_plugin(self):
        template = Template("{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}")
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        placeholder1 = page1.placeholders.filter(slot="body")[0]
        placeholder2 = page1.placeholders.filter(slot="right-column")[0]
        plugin_pool.register_plugin(NoCachePlugin)
        add_plugin(placeholder1, "TextPlugin", 'en', body="English")
        add_plugin(placeholder2, "TextPlugin", 'en', body="Deutsch")

        request = self.get_request('/en/')
        request.current_page = Page.objects.get(pk=page1.pk)
        request.toolbar = CMSToolbar(request)
        template = Template("{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}")
        rctx = RequestContext(request)
        with self.assertNumQueries(3):
            template.render(rctx)

        request = self.get_request('/en/')
        request.current_page = Page.objects.get(pk=page1.pk)
        request.toolbar = CMSToolbar(request)
        template = Template("{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}")
        rctx = RequestContext(request)
        with self.assertNumQueries(1):
            template.render(rctx)
        add_plugin(placeholder1, "NoCachePlugin", 'en')
        page1.publish('en')
        request = self.get_request('/en/')
        request.current_page = Page.objects.get(pk=page1.pk)
        request.toolbar = CMSToolbar(request)
        template = Template("{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}")
        rctx = RequestContext(request)
        with self.assertNumQueries(4):
            render = template.render(rctx)
        with self.assertNumQueries(FuzzyInt(14, 18)):
            response = self.client.get('/en/')
            resp1 = response.content.decode('utf8').split("$$$")[1]

        request = self.get_request('/en/')
        request.current_page = Page.objects.get(pk=page1.pk)
        request.toolbar = CMSToolbar(request)
        template = Template("{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}")
        rctx = RequestContext(request)
        with self.assertNumQueries(4):
            render2 = template.render(rctx)
        with self.assertNumQueries(FuzzyInt(10, 14)):
            response = self.client.get('/en/')
            resp2 = response.content.decode('utf8').split("$$$")[1]
        self.assertNotEqual(render, render2)
        self.assertNotEqual(resp1, resp2)

        plugin_pool.unregister_plugin(NoCachePlugin)
Example #7
0
    def test_sekizai_plugin(self):
        page1 = create_page("test page 1", "nav_playground.html", "en", published=True)

        placeholder1 = page1.placeholders.filter(slot="body")[0]
        placeholder2 = page1.placeholders.filter(slot="right-column")[0]
        plugin_pool.register_plugin(SekizaiPlugin)
        add_plugin(placeholder1, "SekizaiPlugin", "en")
        add_plugin(placeholder2, "TextPlugin", "en", body="Deutsch")
        page1.publish("en")
        response = self.client.get("/en/")
        self.assertContains(response, "alert(")
        response = self.client.get("/en/")
        self.assertContains(response, "alert(")
Example #8
0
    def test_sekizai_plugin(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        placeholder1 = page1.placeholders.filter(slot="body")[0]
        placeholder2 = page1.placeholders.filter(slot="right-column")[0]
        plugin_pool.register_plugin(SekizaiPlugin)
        add_plugin(placeholder1, "SekizaiPlugin", 'en')
        add_plugin(placeholder2, "TextPlugin", 'en', body="Deutsch")
        page1.publish('en')
        response = self.client.get('/en/')
        self.assertContains(response, 'alert(')
        response = self.client.get('/en/')
        self.assertContains(response, 'alert(')
Example #9
0
    def test_no_cache_plugin(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        placeholder1 = page1.placeholders.filter(slot="body")[0]
        placeholder2 = page1.placeholders.filter(slot="right-column")[0]
        plugin_pool.register_plugin(NoCachePlugin)
        add_plugin(placeholder1, "TextPlugin", 'en', body="English")
        add_plugin(placeholder2, "TextPlugin", 'en', body="Deutsch")

        request = self.get_request('/en/')
        request.current_page = Page.objects.get(pk=page1.pk)
        request.toolbar = CMSToolbar(request)
        template = "{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}"
        with self.assertNumQueries(3):
            self.render_template_obj(template, {}, request)

        request = self.get_request('/en/')
        request.current_page = Page.objects.get(pk=page1.pk)
        request.toolbar = CMSToolbar(request)
        template = "{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}"
        with self.assertNumQueries(1):
            self.render_template_obj(template, {}, request)
        add_plugin(placeholder1, "NoCachePlugin", 'en')
        page1.publish('en')
        request = self.get_request('/en/')
        request.current_page = Page.objects.get(pk=page1.pk)
        request.toolbar = CMSToolbar(request)
        template = "{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}"
        with self.assertNumQueries(4):
            output = self.render_template_obj(template, {}, request)
        with self.assertNumQueries(FuzzyInt(14, 19)):
            response = self.client.get('/en/')
            resp1 = response.content.decode('utf8').split("$$$")[1]

        request = self.get_request('/en/')
        request.current_page = Page.objects.get(pk=page1.pk)
        request.toolbar = CMSToolbar(request)
        template = "{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}"
        with self.assertNumQueries(4):
            output2 = self.render_template_obj(template, {}, request)
        with self.settings(CMS_PAGE_CACHE=False):
            with self.assertNumQueries(FuzzyInt(8, 13)):
                response = self.client.get('/en/')
                resp2 = response.content.decode('utf8').split("$$$")[1]
        self.assertNotEqual(output, output2)
        self.assertNotEqual(resp1, resp2)

        plugin_pool.unregister_plugin(NoCachePlugin)
Example #10
0
 def test_07_register_plugin_twice_should_raise(self):
     number_of_plugins_before = len(plugin_pool.get_all_plugins())
     # The first time we register the plugin is should work
     plugin_pool.register_plugin(DumbFixturePlugin)
     # Let's add it a second time. We should catch and exception
     raised = False
     try:
         plugin_pool.register_plugin(DumbFixturePlugin)
     except PluginAlreadyRegistered:
         raised = True
     self.assertTrue(raised)
     # Let's also unregister the plugin now, and assert it's not in the 
     # pool anymore
     plugin_pool.unregister_plugin(DumbFixturePlugin)
     # Let's make sure we have the same number of plugins as before:
     number_of_plugins_after = len(plugin_pool.get_all_plugins())
     self.assertEqual(number_of_plugins_before, number_of_plugins_after)
Example #11
0
    def test_timedelta_cache_plugin(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        placeholder1 = page1.placeholders.filter(slot="body")[0]
        placeholder2 = page1.placeholders.filter(slot="right-column")[0]
        plugin_pool.register_plugin(TimeDeltaCacheExpirationPlugin)
        add_plugin(placeholder1, "TextPlugin", 'en', body="English")
        add_plugin(placeholder2, "TextPlugin", 'en', body="Deutsch")

        # Add *TimeDeltaCacheExpirationPlugin, expires in 45s.
        add_plugin(placeholder1, "TimeDeltaCacheExpirationPlugin", 'en')

        # Ensure that we're testing in an environment WITHOUT the MW cache, as
        # we are testing the internal page cache, not the MW cache.
        exclude = [
            'django.middleware.cache.UpdateCacheMiddleware',
            'django.middleware.cache.CacheMiddleware',
            'django.middleware.cache.FetchFromCacheMiddleware',
        ]
        overrides = dict()
        if getattr(settings, 'MIDDLEWARE', None):
            overrides['MIDDLEWARE'] = [mw for mw in settings.MIDDLEWARE if mw not in exclude]
        else:
            overrides['MIDDLEWARE_CLASSES'] = [mw for mw in settings.MIDDLEWARE_CLASSES if mw not in exclude]
        with self.settings(**overrides):
            page1.publish('en')
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(FuzzyInt(14, 25)):  # was 14, 24
                response = self.client.get('/en/')

            self.assertTrue('max-age=45' in response['Cache-Control'], response['Cache-Control'])

        plugin_pool.unregister_plugin(TimeDeltaCacheExpirationPlugin)
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _
from shop_richcatalog.models import CatalogPlugin
from shop_richcatalog.models import Catalog


class CMSCatalogPlugin(CMSPluginBase):
    model = CatalogPlugin
    name = _("Catalog")
    render_template = "catalog/catalog_grid_plugin.html"

    def render(self, context, instance, placeholder):
        context['catalog_list'] = Catalog.objects.all()
        return context

plugin_pool.register_plugin(CMSCatalogPlugin)
Example #13
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.forms import widgets
from django.utils.translation import ugettext_lazy as _

from cms.plugin_pool import plugin_pool
from cmsplugin_cascade.fields import GlossaryField
from cmsplugin_cascade.plugin_base import CascadePluginBase


class Badge(CascadePluginBase):
    """
    This is a simple example of a plugin suitable for the djangocms-cascade system.
    It contains one single field: `content` rendered via the template `bs4demo/badge.html`.
    """
    name = _("Badge")
    require_parent = False
    allow_children = False
    render_template = 'bs4demo/badge.html'

    content = GlossaryField(
        widgets.TextInput(),
        label=_("Content"),
    )

plugin_pool.register_plugin(Badge)
Example #14
0
    model = ConceptsPluginModel  # model where plugin data are saved
    module = _("Data Commons")
    name = _("Link Concepts")  # name of the plugin in the interface
    render_template = "focus/featured_concepts.html"
    form = modelform_factory(ConceptsPluginModel,
                             exclude=[],
                             widgets={
                                 'concepts': ConceptTagAdminWidget,
                             })

    def render(self, context, instance, placeholder):
        context.update({'concepts': instance.concepts.all()})
        return context


plugin_pool.register_plugin(ConceptsPluginPublisher)  # register the plugin


#CONSIDE: recent datasets vs new datasets vs stories- concept level?
#TODO search form? publishers?
@plugin_pool.register_plugin
class CallToActionPluginPublisher(CMSPluginBase):
    model = CallToActionPluginModel
    module = _("Data Commons")
    name = _("Call To Action")
    render_template = "focus/call_to_action.html"

    def render(self, context, instance, placeholder):
        context.update({'widget': instance})
        return context
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _
import models
import settings

class SimpleGalleryPlugin(CMSPluginBase):
    model = models.SimpleGalleryPointer
    name = _('Simple: Image gallery')
    render_template = settings.CMS_SIMPLEGALLERY_DEFAULT_TEMPLATE
    text_enabled = True

    def render(self, context, instance, placeholder):
        context.update({
            'images': instance.gallery.simpleimage_set.all(),
            'placeholder':placeholder
        })
        self.render_template = instance.template
        return context

    def icon_src(self, instance):
        return instance.gallery.simpleimage_set.all()[0].get_thumbnail()

plugin_pool.register_plugin(SimpleGalleryPlugin)
Example #16
0
from .models import (
    TestPluginModel,
    TestPluginModel2,
    TestPluginModel3,
    TestPluginModel4,
    TestPluginModel5,
)


class TestPlugin(CMSPluginBase):
    model = TestPluginModel
    render_template = 'cms/content.html'


plugin_pool.register_plugin(TestPlugin)


class TestPlugin2(CMSPluginBase):
    model = TestPluginModel2
    render_template = 'cms/content.html'


plugin_pool.register_plugin(TestPlugin2)


class TestPlugin3(CMSPluginBase):
    model = TestPluginModel3
    render_template = 'cms/content.html'

Example #17
0
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from cms.models.pluginmodel import CMSPlugin

from django.utils.translation import ugettext_lazy as _

from .models import ContactPluginModel

class ContactPlugin(CMSPluginBase):
    model = ContactPluginModel
    name = _("CPM Contact Plugin")
    render_template = "contact_plugin.html"

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        return context

plugin_pool.register_plugin(ContactPlugin);


        for slide in instance.slides.all().order_by('order'):
            if slide.is_playlist:
                response = requests.get(slide.playlist_link)
                if response.status_code == 200:
                    xml = BytesIO(response.content)
                    xml.flush()
                    xml.seek(0)
                    for entry in ET.parse(xml).getroot().findall(
                            u"{http://www.w3.org/2005/Atom}entry"):
                        video_id = slide.video_id(
                            entry.findall(u"{http://www.w3.org/2005/Atom}link")
                            [0].attrib.get('href', 'X'))
                        slides.append(
                            YoutubeVideo(pos.next(), video_id,
                                         slide.video_thumb(video_id)))
            else:
                slides.append(
                    YoutubeVideo(pos.next(), slide.video_id,
                                 slide.video_thumb))

        context.update({
            'slides': slides,
            'description': instance.description.strip()
        })

        return context


plugin_pool.register_plugin(YoutubeSliderPlugin)
from django.utils.importlib import import_module

from .forms import FeedbackMessageForm
from .models import FeedbackPlugin as Plugin


class FeedbackPlugin(CMSPluginBase):
    model = Plugin
    name = _('Feedback Plugin')
    render_template = 'cms/plugins/feedback.html'

    @property
    def _message_form(self):
        form = getattr(settings, 'CMS_FEEDBACK_FORM', None)
        if form:
            module, cls = form.rsplit('.', 1)
            return getattr(import_module(module), cls)
        return FeedbackMessageForm

    def get_message_form(self, *args, **kwargs):
        return self._message_form(*args, **kwargs)

    def render(self, context, instance, placeholder):
        context.update({
            'instance': instance,
            'form': self.get_message_form(),
        })
        return context

plugin_pool.register_plugin(FeedbackPlugin)
Example #20
0
        except:  # noqa
            # I use a "catch all" in order to not couple this handler to a specific email backend
            # different email backends have different exceptions.
            logger.exception("Could not send notification emails.")
            return []

        notifications = instance.email_notifications.select_related('form')

        emails = []
        recipients = []

        for notification in notifications:
            email = notification.prepare_email(form=form)

            to_email = email.to[0]

            if is_valid_recipient(to_email):
                emails.append(email)
                recipients.append(parseaddr(to_email))

        try:
            connection.send_messages(emails)
        except:  # noqa
            # again, we catch all exceptions to be backend agnostic
            logger.exception("Could not send notification emails.")
            recipients = []
        return recipients


plugin_pool.register_plugin(EmailNotificationForm)
Example #21
0
            kwargs["queryset"] = Game.objects.filter(match__published=True, winner_team__isnull=False, match__tournament=getattr(self.obj, 'tournament', None)) \
                                             .order_by('-match__publish_date') \
                                             .select_related('home_player', 'away_player', 'map') \
                                             .only('home_player__char_name', 'away_player__char_name', 'map__name')
        return super(GamePlugin,
                     self).formfield_for_foreignkey(db_field, request,
                                                    **kwargs)

    def render(self, context, instance, placeholder):
        context['game'] = instance.game
        if instance.game:
            context['match'] = instance.game.match
        return context


plugin_pool.register_plugin(GamePlugin)


class RandomTeamsPlugin(CMSPluginBase):
    model = TournamentPluginModel
    name = _("Random Teams")
    render_template = "tournaments/random_teams_plugin.html"

    def render(self, context, instance, placeholder):
        context['tournament'] = instance.tournament
        return context


plugin_pool.register_plugin(RandomTeamsPlugin)

Example #22
0
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _

from .models import IncomeDeclaration, IncomeDeclarationPluginConf

NUM_RECORDS = 5


class IncomeDeclarationPlugin(CMSPluginBase):
    model = IncomeDeclarationPluginConf
    name = _('Income Declaration Plugin')
    render_template = 'cmsplugins/incomedeclaration.html'

    def render(self, context, instance, placeholder):
        context['instance'] = instance

        obj_list = IncomeDeclaration.objects.all()
        context['obj_list'] = obj_list[:NUM_RECORDS]

        return context


plugin_pool.register_plugin(IncomeDeclarationPlugin)
Example #23
0
try:
    import urllib.parse
except ImportError:
    from urllib import parse as urlparse

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from designsafe.apps.cms_plugins.models import ResponsiveEmbedPlugin
from django.conf import settings
from django.utils.translation import ugettext as _


class CMSResponsiveEmbedPlugin(CMSPluginBase):
    model = ResponsiveEmbedPlugin  # model where plugin data are saved
    module = _("Bootstrap")
    name = _("Responsive Embed")  # name of the plugin in the interface
    text_enabled = True
    render_template = "cms_plugins/responsive_embed_plugin.html"

    def render(self, context, instance, placeholder):
        context.update({'instance': instance})
        return context

    def icon_src(self, instance):
        return urllib.parse.urljoin(
            settings.STATIC_URL, "cms/img/icons/plugins/image.png")

plugin_pool.register_plugin(CMSResponsiveEmbedPlugin)  # register the plugin
Example #24
0
    require_parent = True
    parent_classes = ['ContactFormCMSPlugin']


class ContactFormDateTimeFieldCMSPlugin(CMSPluginBase):
    model = models.ContactFormTextFieldCMS
    name = 'Date & Time Field'
    render_template = 'cmsplugin_contact_form_3.0.7/datetime_field.html'
    require_parent = True
    parent_classes = ['ContactFormCMSPlugin']


class ContactFormSubmitFieldCMSPlugin(CMSPluginBase):
    model = models.ContactFormSubmitFieldCMS
    name = 'Submit Field'
    render_template = 'cmsplugin_contact_form_3.0.7/submit_field.html'
    require_parent = True
    parent_classes = ['ContactFormCMSPlugin']
    

plugin_pool.register_plugin(ContactFormCMSPlugin)
plugin_pool.register_plugin(ContactFormTextFieldCMSPlugin)
plugin_pool.register_plugin(ContactFormEmailFieldCMSPlugin)
plugin_pool.register_plugin(ContactFormPhoneFieldCMSPlugin)
plugin_pool.register_plugin(ContactFormTextAreaFieldCMSPlugin)
plugin_pool.register_plugin(ContactFormCheckboxFieldCMSPlugin)
plugin_pool.register_plugin(ContactFormRadioFieldCMSPlugin)
plugin_pool.register_plugin(ContactFormDateFieldCMSPlugin)
plugin_pool.register_plugin(ContactFormTimeFieldCMSPlugin)
plugin_pool.register_plugin(ContactFormDateTimeFieldCMSPlugin)
plugin_pool.register_plugin(ContactFormSubmitFieldCMSPlugin)
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.contrib import admin
from django.template import Context, Template
from django.utils.translation import ugettext as _
from models import *
from settings import *


class CMSSimpleNewsPlugin(CMSPluginBase):
    model = SimpleNewsExcerptPlugin
    name = _("Simple news excerpt")
    render_template = "cmsplugin_simplenews/simple_news.html"
    
    def render(self, context, instance, placeholder):
        context.update({
            'news': instance.get_news_set(),
        })
        return context


plugin_pool.register_plugin(CMSSimpleNewsPlugin)
Example #26
0
        return context

    def get_form(self, request, obj=None, **kwargs):
        Form = super(InheritPagePlaceholderPlugin,
                     self).get_form(request, obj, **kwargs)

        # this is bit tricky, since i don't wont override add_view and
        # change_view
        class FakeForm(object):
            def __init__(self, Form, site):
                self.Form = Form
                self.site = site

                # base fields are required to be in this fake class, this may
                # do some troubles, with new versions of django, if there will
                # be something more required
                self.base_fields = Form.base_fields

            def __call__(self, *args, **kwargs):
                # instanciate the form on call
                form = self.Form(*args, **kwargs)
                # tell form we are on this site
                form.for_site(self.site)
                return form

        return FakeForm(Form, self.cms_plugin_instance.page.site
                        or self.page.site)


plugin_pool.register_plugin(InheritPagePlaceholderPlugin)
Example #27
0
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
from models import File
from django.conf import settings
from cms.settings import CMS_MEDIA_URL

class FilePlugin(CMSPluginBase):
    model = File
    name = _("File")
    render_template = "cms/plugins/file.html"
    text_enabled = True
    
    def render(self, context, instance, placeholder):  
        context.update({
            'object':instance, 
            'placeholder':placeholder
        })    
        return context

    def icon_src(self, instance):
        file_icon = instance.get_icon_url()
        if file_icon: return file_icon
        return CMS_MEDIA_URL + u"images/plugins/file.png"
    
plugin_pool.register_plugin(FilePlugin)
Example #28
0
    change_form_template = 'admin/aldryn_bootstrap3/base.html'
    cache = True

    def render(self, context, instance, placeholder):
        context['testimonial_box'] = instance
        return context


class ColoredAreaPlugin(WebsitePlugin):
    render_template = 'plugins/colored_area.html'
    allow_children = True
    cache = False
    name = 'Content area'
    model = ColoredAreaBox


class DownloadSoftwareButtonPlugin(WebsitePlugin):
    render_template = 'plugins/download_software_button.html'
    allow_children = True
    cache = False
    name = 'Download software button'
    model = DownloadSoftwareButton


plugin_pool.register_plugin(SoftwarePricingPlugin)
plugin_pool.register_plugin(SoftwareSpecificPricingPlugin)
plugin_pool.register_plugin(SoftwareDownloadPlugin)
plugin_pool.register_plugin(PromotionalBoxPlugin)
plugin_pool.register_plugin(TestimonialBoxPlugin)
plugin_pool.register_plugin(ColoredAreaPlugin)
plugin_pool.register_plugin(DownloadSoftwareButtonPlugin)
Example #29
0
    fieldsets = copy.deepcopy(PicturePlugin.fieldsets)
    fieldsets[0] = (None, {
        'fields': (
            'picture',
            'external_picture',
            ('picture_fluid', 'picture_rounded', 'picture_thumbnail'),
        )
    })

    def render(self, context, instance, placeholder):
        link_classes = []
        if instance.picture_fluid:
            link_classes.append('img-fluid')
        if instance.picture_rounded:
            link_classes.append('rounded')
        if instance.picture_thumbnail:
            link_classes.append('img-thumbnail')

        classes = concat_classes(link_classes + [
            instance.attributes.get('class'),
        ])
        instance.attributes['class'] = classes

        return super(Bootstrap4PicturePlugin,
                     self).render(context, instance, placeholder)


plugin_pool.unregister_plugin(PicturePlugin)
plugin_pool.register_plugin(Bootstrap4PicturePlugin)
Example #30
0
                max_widths[bp] = parent_glossary['container_max_widths'][bp]
            except KeyError:
                max_widths[bp] = CASCADE_BREAKPOINTS_DICT[bp][3]
            if last_index > 0:
                if index == 0:
                    next_bp = breakpoints[1]
                    media_queries[bp] = ['(max-width: {0}px)'.format(CASCADE_BREAKPOINTS_DICT[next_bp][0])]
                elif index == last_index:
                    media_queries[bp] = ['(min-width: {0}px)'.format(CASCADE_BREAKPOINTS_DICT[bp][0])]
                else:
                    next_bp = breakpoints[index + 1]
                    media_queries[bp] = ['(min-width: {0}px)'.format(CASCADE_BREAKPOINTS_DICT[bp][0]),
                                         '(max-width: {0}px)'.format(CASCADE_BREAKPOINTS_DICT[next_bp][0])]
        return sanitized

plugin_pool.register_plugin(BootstrapContainerPlugin)


class BootstrapRowForm(ManageChildrenFormMixin, ModelForm):
    """
    Form class to add non-materialized field to count the number of children.
    """
    ROW_NUM_COLUMNS = (1, 2, 3, 4, 6, 12,)
    num_children = ChoiceField(choices=tuple((i, ungettext_lazy('{0} column', '{0} columns', i).format(i)) for i in ROW_NUM_COLUMNS),
        initial=3, label=_('Columns'),
        help_text=_('Number of columns to be created with this row.'))


class BootstrapRowPlugin(BootstrapPluginBase):
    name = _("Row")
    default_css_class = 'row'
Example #31
0
    fieldsets = [
        (None, {
            'fields': (
                'figure_caption',
                'figure_alignment',
            )
        }),
        (_('Advanced settings'), {
            'classes': ('collapse',),
            'fields': (
                'attributes',
            )
        }),
    ]

    def render(self, context, instance, placeholder):
        classes = concat_classes([
            'figure',
            instance.attributes.get('class'),
        ])
        instance.attributes['class'] = classes

        return super(Bootstrap4FigurePlugin, self).render(
            context, instance, placeholder
        )


plugin_pool.register_plugin(Bootstrap4CodePlugin)
plugin_pool.register_plugin(Bootstrap4BlockquotePlugin)
plugin_pool.register_plugin(Bootstrap4FigurePlugin)
Example #32
0
                obj.glossary['media_queries'][bp.name]['width'] = width
                sanitized = True
            if obj.glossary['media_queries'][bp.name].get(
                    'media') != bp.media_query:
                obj.glossary['media_queries'][
                    bp.name]['media'] = bp.media_query
                sanitized = True
        return sanitized

    @classmethod
    def get_css_classes(cls, obj):
        css_classes = cls.super(BootstrapJumbotronPlugin,
                                cls).get_css_classes(obj)
        if obj.glossary.get('fluid'):
            css_classes.append('jumbotron-fluid')
        else:
            css_classes.append('jumbotron')
        return css_classes

    @classmethod
    def get_identifier(cls, obj):
        identifier = super().get_identifier(obj)
        try:
            content = obj.image.name or obj.image.original_filename
        except AttributeError:
            content = _("Without background image")
        return format_html('{0}{1}', identifier, content)


plugin_pool.register_plugin(BootstrapJumbotronPlugin)
Example #33
0
# Generate Column Plugin classes and register them
COLUMNS = [
    (3, _('Three')),
    (4, _('Four')),
    (6, _('Six')),
    (8, _('Eight')),
    (9, _('Nine')),
    (12, _('Twelve')),
]

for col_count, col_name in COLUMNS:
    plugin_pool.register_plugin(
        type(
            'Column%sPlugin' % col_count,
            (ColumnPlugin,),
            {
                'name': _("Column " + str(col_name)),
                'render_template': "cms/plugins/col_%d.html" % col_count,
            }
        )
    )


@plugin_pool.register_plugin
class ColumnTeaserPlugin(CMSPluginBase):
    module = _("Structure")
    allow_children = True
    name = _('Column Teaser Three')
    render_template = 'cms/plugins/col_teaser.html'


@plugin_pool.register_plugin
Example #34
0
        form = CaptchaFieldForm
        form_field = CaptchaField
        form_field_widget = CaptchaTextInput
        form_field_enabled_options = ['label', 'error_messages']
        fieldset_general_fields = [
            'label',
        ]
        fieldset_advanced_fields = [
            'required_message',
        ]

        def serialize_field(self, *args, **kwargs):
            # None means don't serialize me
            return None

    plugin_pool.register_plugin(CaptchaField)


class SubmitButton(FormElement):
    render_template = 'aldryn_forms/submit_button.html'
    name = _('Submit Button')
    model = models.FormButtonPlugin


plugin_pool.register_plugin(BooleanField)
plugin_pool.register_plugin(EmailField)
plugin_pool.register_plugin(FileField)
plugin_pool.register_plugin(ImageField)
plugin_pool.register_plugin(Fieldset)
plugin_pool.register_plugin(FormPlugin)
plugin_pool.register_plugin(MultipleSelectField)
Example #35
0
from .forms import FeedbackMessageForm
from .models import FeedbackPlugin as Plugin


class FeedbackPlugin(CMSPluginBase):
    model = Plugin
    name = _('Feedback Plugin')
    render_template = 'cms/plugins/feedback.html'

    @property
    def _message_form(self):
        form = getattr(settings, 'CMS_FEEDBACK_FORM', None)
        if form:
            module, cls = form.rsplit('.', 1)
            return getattr(import_module(module), cls)
        return FeedbackMessageForm

    def get_message_form(self, *args, **kwargs):
        return self._message_form(*args, **kwargs)

    def render(self, context, instance, placeholder):

        context.update({
            'instance': instance,
            'form': self.get_message_form(),
        })
        return context


plugin_pool.register_plugin(FeedbackPlugin)
Example #36
0
class AppCategoryPlugin(AppPlugin):
    module = _('App')
    name = _('Categories')
    model = CMSPlugin
    render_template = 'plugins/categories.html'

    def render(self, context, instance, placeholder):
        context = super(AppCategoryPlugin, self).render(context, instance, placeholder)
        context['categories'] = AppCategory.objects.all()
        return context


class AppArchivePlugin(AppPlugin):
    module = _('App')
    name = _('Archive')
    model = CMSPlugin
    render_template = 'plugins/archive.html'

    def render(self, context, instance, placeholder):
        context = super(AppArchivePlugin, self).render(context, instance, placeholder)
        context['dates'] = Terms.objects.get_months(queryset=Terms.objects.published())
        return context


plugin_pool.register_plugin(AppLatestEntriesPlugin)
plugin_pool.register_plugin(AppAuthorTermsPlugin)
plugin_pool.register_plugin(AppTagsPlugin)
plugin_pool.register_plugin(AppArchivePlugin)
plugin_pool.register_plugin(AppCategoryPlugin)
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _

from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase

from .models import Teaser


class TeaserPlugin(CMSPluginBase):
    model = Teaser
    name = _("teaser")
    render_template = "plugins/teaser/teaser.html"
    text_enabled = False
    admin_preview = False
    
    def render(self, context, instance, placeholder):
        context.update({
            'teaser': instance,
            'placeholder': placeholder
        })
        return context 

plugin_pool.register_plugin(TeaserPlugin)
            def __init__(self, Form, site):
                self.Form = Form
                self.site = site
                self.base_fields = Form.base_fields

            def __call__(self, *args, **kwargs):
                # instantiate the form on call
                form = self.Form(*args, **kwargs)
                return form

        if self.cms_plugin_instance.page and self.cms_plugin_instance.page.site:
            site = self.cms_plugin_instance.page.site
        elif self.page and self.page.site:
            site = self.page.site
        else:
            site = Site.objects.get_current()

        return FakeForm(Form, site)

    def icon_src(self, instance):
        if instance.link == '':
            return settings.STATIC_URL + u'djangocms_styledlink/images/link-error.png'
        else:
            return settings.STATIC_URL + u'djangocms_styledlink/images/link.png'

    def icon_alt(self, instance):
        return u'%s - %s' % (self.name, instance.label)


plugin_pool.register_plugin(StyledLinkPlugin)
Example #39
0
print "in VideoPluginPlublisher"
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
import models
from arkestra_utilities.output_libraries.plugin_widths import *

class VideoPluginPublisher(CMSPluginBase):
    model = models.VideoPluginEditor
    name = _("Video new")
    render_template = "video/video.html"
    text_enabled = False
    raw_id_fields = ('image',)
            
    def render(self, context, instance, placeholder):
        context.update({
            'object':instance,
            'placeholder':placeholder,
            })
        return context

    def icon_src(self, instance):
        return "instance.image.thumbnails['admin_tiny_icon']"

plugin_pool.register_plugin(VideoPluginPublisher)
Example #40
0
class VideoTrackPlugin(CMSPluginBase):
    model = models.VideoTrack
    name = _('Track')
    module = _('Video player')
    require_parent = True
    parent_classes = ['VideoPlayerPlugin']

    fieldsets = [(None, {
        'fields': (
            'kind',
            'src',
            'srclang',
        )
    }),
                 (_('Advanced settings'), {
                     'classes': ('collapse', ),
                     'fields': (
                         'label',
                         'attributes',
                     )
                 })]

    def get_render_template(self, context, instance, placeholder):
        return 'djangocms_video/{}/track.html'.format(
            context['video_template'])


plugin_pool.register_plugin(VideoPlayerPlugin)
plugin_pool.register_plugin(VideoSourcePlugin)
plugin_pool.register_plugin(VideoTrackPlugin)
from cms.plugin_pool import plugin_pool
from cmsplugin_cascade.fields import PartialFormField
from cmsplugin_cascade.utils import resolve_dependencies
from .plugin_base import LinkPluginBase, LinkElementMixin
from .forms import TextLinkForm


class TextLinkPlugin(LinkPluginBase):
    name = _("Link")
    form = TextLinkForm
    model_mixins = (LinkElementMixin,)
    render_template = 'cascade/plugins/link.html'
    glossary_fields = (
        PartialFormField('title',
            widgets.TextInput(),
            label=_("Title"),
            help_text=_("Link's Title")
        ),
    ) + LinkPluginBase.glossary_fields
    html_tag_attributes = dict(title='title', **LinkPluginBase.html_tag_attributes)
    fields = ('link_content', ('link_type', 'cms_page', 'ext_url', 'mail_to'), 'glossary',)

    class Media:
        js = resolve_dependencies('cascade/js/admin/linkplugin.js')

    @classmethod
    def get_identifier(cls, obj):
        return mark_safe(obj.glossary.get('link_content', ''))

plugin_pool.register_plugin(TextLinkPlugin)
# -*- coding: utf-8 -*-

from django.conf import settings

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from .models import TabsPluginModel


class TabsPlugin(CMSPluginBase):
    name = U'Tabs'
    model = TabsPluginModel
    render_template = "tabs/_tabs_plugin.html"
    text_enabled = True

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        return context

    def icon_src(self, instance):
        return settings.STATIC_URL + 'tabs/images/tabs_icon.png'

    def icon_alt(self, instance):
        return u'Tabs: %s' % instance


plugin_pool.register_plugin(TabsPlugin)
Example #43
0
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
from cms.plugins.picture.models import Picture
from cms.settings import CMS_MEDIA_URL

class PicturePlugin(CMSPluginBase):
    model = Picture
    name = _("Picture")
    render_template = "cms/plugins/picture.html"
    text_enabled = True
    
    def render(self, context, instance, placeholder):
        if instance.url:
            link = instance.url
        elif instance.page_link:
            link = instance.page_link.get_absolute_url()
        else:
            link = ""
        context.update({
            'picture':instance,
            'link':link, 
            'placeholder':placeholder
        })
        return context 
    
    def icon_src(self, instance):
        # TODO - possibly use 'instance' and provide a thumbnail image
        return CMS_MEDIA_URL + u"images/plugins/image.png"
 
plugin_pool.register_plugin(PicturePlugin)
Example #44
0
    admin_preview = False
    text_enabled = True
    # the form renders to plugin_detail.html, which then uses
    # {% include form_template_name %}
    render_template = "html/formdefinition/plugin_detail.html"

    def render(self, context, instance, placeholder):

        context.update({
            'form_template_name':
            instance.form_definition.form_template_name
            or settings.DEFAULT_FORM_TEMPLATE,
        })

        disable_redirection = 'form_designer.middleware.RedirectMiddleware' not in django_settings.MIDDLEWARE_CLASSES

        response = process_form(context['request'],
                                instance.form_definition,
                                context,
                                disable_redirection=disable_redirection)

        if isinstance(response, HttpResponseRedirect):
            raise HttpRedirectException(response, "Redirect")
        return response

    def icon_src(self, instance):
        return "/static/plugin_icons/form.png"


plugin_pool.register_plugin(FormDesignerPlugin)
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_pagedown.forms import PagedownForm
from cmsplugin_pagedown.models import PagedownConfig
from django.utils.translation import ugettext as _


class PagedownPlugin(CMSPluginBase):
    form = PagedownForm
    model = PagedownConfig
    name = _("Pagedown Markdown")
    render_template = "cmsplugin_pagedown/markdown.html"
    admin_preview = False
    fieldsets = [
        ("", {'fields': ('markdown',)}),
        ("CSS", {'fields': ('css_classes', 'css_id', )}),
    ]

    def render(self, context, instance, placeholder):
        context.update({
            'instance': instance,
        })
        return context

plugin_pool.register_plugin(PagedownPlugin)
Example #46
0
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext as _
from models import VimeoSecure


class VimeoSecurePlugin(CMSPluginBase):
    model = VimeoSecure
    name = _("Vimeo")
    render_template = "cms/plugins/vimeosecure.html"

    def render(self, context, instance, placeholder):
        context.update({'object': instance, 'placeholder': placeholder})
        return context


plugin_pool.register_plugin(VimeoSecurePlugin)
Example #47
0
            return context

        else:
            context.update({
                'contact': instance,
                'form': form,
            })
        return context

    def send(self, form, site_email, attachments=None):
        subject = render_to_string(self.topic_template, {'data': form.cleaned_data}).strip().splitlines()[0]
        body = render_to_string(self.body_template, {'data': form.cleaned_data, 'fields': form.fields})
        # TODO add template tag to get the select value of a choices field

        if 'email' in form.cleaned_data and form.cleaned_data['email']:
            email = form.cleaned_data['email']
        else:
            email = site_email
        
        if not subject:
            subject = 'Kein Betreff'

        email_message = EmailMessage(subject.encode("UTF8"), body.encode("UTF8"), email, [site_email], headers = {'Reply-To':email})

        if attachments:
            for var_name, data in attachments.iteritems():
                email_message.attach(data.name, data.read(), data.content_type)
        email_message.send(fail_silently=False)

plugin_pool.register_plugin(MailformPlugin)
    name = _("Soundcloud")
    render_template = "cmsplugin_soundcloud/embed.html"

    def render(self, context, instance, placeholder):
        context.update({
            'object': instance,
            'placeholder': placeholder,
            'ids': self.extract_track_id(instance.url)
        })
        return context
    
    
    def extract_track_id(self, url):
        
        REGEX_PATTERN = '^http://soundcloud.com/(?P<user_id>[-\w]+)/(?P<track_id>[-\w]+)/$'
        
        p = re.compile(REGEX_PATTERN)
        m = p.search(url)

        try:
            user_id = m.group('user_id')
            track_id = m.group('track_id')
        except Exception, e:
            print e
            user_id  = None
            track_id  = None
            
        return user_id, track_id

plugin_pool.register_plugin(SoundcloudPlugin)
Example #49
0
    def test_no_cache_plugin(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        placeholder1 = page1.placeholders.filter(slot='body')[0]
        placeholder2 = page1.placeholders.filter(slot='right-column')[0]
        try:
            plugin_pool.register_plugin(NoCachePlugin)
        except PluginAlreadyRegistered:
            pass
        add_plugin(placeholder1, 'TextPlugin', 'en', body="English")
        add_plugin(placeholder2, 'TextPlugin', 'en', body="Deutsch")
        template = "{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}"

        # Ensure that we're testing in an environment WITHOUT the MW cache, as
        # we are testing the internal page cache, not the MW cache.
        exclude = [
            'django.middleware.cache.UpdateCacheMiddleware',
            'django.middleware.cache.CacheMiddleware',
            'django.middleware.cache.FetchFromCacheMiddleware'
        ]
        overrides = dict()
        if getattr(settings, 'MIDDLEWARE', None):
            overrides['MIDDLEWARE'] = [mw for mw in settings.MIDDLEWARE if mw not in exclude]
        else:
            overrides['MIDDLEWARE_CLASSES'] = [mw for mw in settings.MIDDLEWARE_CLASSES if mw not in exclude]
        with self.settings(**overrides):
            # Request the page without the 'no-cache' plugin
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(FuzzyInt(18, 25)):
                response1 = self.client.get('/en/')
                content1 = response1.content

            # Fetch it again, it is cached.
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(0):
                response2 = self.client.get('/en/')
                content2 = response2.content
            self.assertEqual(content1, content2)

            # Once again with PAGE_CACHE=False, to prove the cache can
            # be disabled
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.settings(CMS_PAGE_CACHE=False):
                with self.assertNumQueries(FuzzyInt(5, 24)):
                    response3 = self.client.get('/en/')
                    content3 = response3.content
            self.assertEqual(content1, content3)

            # Add the 'no-cache' plugin
            add_plugin(placeholder1, "NoCachePlugin", 'en')
            page1.publish('en')
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(FuzzyInt(4, 6)):
                output = self.render_template_obj(template, {}, request)
            with self.assertNumQueries(FuzzyInt(14, 24)):
                response = self.client.get('/en/')
                self.assertTrue("no-cache" in response['Cache-Control'])
                resp1 = response.content.decode('utf8').split("$$$")[1]

            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(4):
                output2 = self.render_template_obj(template, {}, request)
            with self.settings(CMS_PAGE_CACHE=False):
                with self.assertNumQueries(FuzzyInt(8, 13)):
                    response = self.client.get('/en/')
                    resp2 = response.content.decode('utf8').split("$$$")[1]
            self.assertNotEqual(output, output2)
            self.assertNotEqual(resp1, resp2)

        plugin_pool.unregister_plugin(NoCachePlugin)
Example #50
0
# _*_ coding: utf-8 _*_
__author__ = 'vitali'
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext as _
from django.template import Context
from .models import Plugin


class SliderPlugin(CMSPluginBase):
    module = _("Our Mega Plugins")  # Раздел где будет сам плагин
    name = _("My plugin")  # Имя плагина, отображается при выборе
    render_template = "plugin/plugin.html"

    model = Plugin  # Система управления плагином, нужно организовать постраничный вывод указать количество и т.п.

    def render(self, context, instance, placeholder):  # instance значения из моделей
        context.update({'instance': instance})
        return context

plugin_pool.register_plugin(SliderPlugin)
Example #51
0
    def test_expiration_cache_plugins(self):
        """
        Tests that when used in combination, the page is cached to the
        shortest TTL.
        """
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        placeholder1 = page1.placeholders.filter(slot="body")[0]
        placeholder2 = page1.placeholders.filter(slot="right-column")[0]
        plugin_pool.register_plugin(TTLCacheExpirationPlugin)
        try:
            plugin_pool.register_plugin(DateTimeCacheExpirationPlugin)
        except PluginAlreadyRegistered:
            pass
        try:
            plugin_pool.register_plugin(NoCachePlugin)
        except PluginAlreadyRegistered:
            pass
        add_plugin(placeholder1, "TextPlugin", 'en', body="English")
        add_plugin(placeholder2, "TextPlugin", 'en', body="Deutsch")

        # Add *CacheExpirationPlugins, one expires in 50s, the other in 40s.
        # The page should expire in the least of these, or 40s.
        add_plugin(placeholder1, "TTLCacheExpirationPlugin", 'en')
        add_plugin(placeholder2, "DateTimeCacheExpirationPlugin", 'en')

        # Ensure that we're testing in an environment WITHOUT the MW cache, as
        # we are testing the internal page cache, not the MW cache.
        exclude = [
            'django.middleware.cache.UpdateCacheMiddleware',
            'django.middleware.cache.CacheMiddleware',
            'django.middleware.cache.FetchFromCacheMiddleware',
        ]
        overrides = dict()
        if getattr(settings, 'MIDDLEWARE', None):
            overrides['MIDDLEWARE'] = [mw for mw in settings.MIDDLEWARE if mw not in exclude]
        else:
            overrides['MIDDLEWARE_CLASSES'] = [mw for mw in settings.MIDDLEWARE_CLASSES if mw not in exclude]
        with self.settings(**overrides):
            page1.publish('en')
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(FuzzyInt(14, 26)):
                response = self.client.get('/en/')
                resp1 = response.content.decode('utf8').split("$$$")[1]
            self.assertTrue('max-age=40' in response['Cache-Control'], response['Cache-Control'])  # noqa
            cache_control1 = response['Cache-Control']
            expires1 = response['Expires']
            last_modified1 = response['Last-Modified']

            time.sleep(1)  # This ensures that the cache has aged measurably

            # Request it again, this time, it comes from the cache
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(0):
                response = self.client.get('/en/')
                resp2 = response.content.decode('utf8').split("$$$")[1]
            # Content will be the same
            self.assertEqual(resp2, resp1)
            # Cache-Control will be different because the cache has aged
            self.assertNotEqual(response['Cache-Control'], cache_control1)
            # However, the Expires timestamp will be the same
            self.assertEqual(response['Expires'], expires1)
            # As will the Last-Modified timestamp.
            self.assertEqual(response['Last-Modified'], last_modified1)

        plugin_pool.unregister_plugin(TTLCacheExpirationPlugin)
        plugin_pool.unregister_plugin(DateTimeCacheExpirationPlugin)
        plugin_pool.unregister_plugin(NoCachePlugin)
Example #52
0
from django.utils.translation import ugettext_lazy as _

from cms import plugin_base
from cms.plugin_pool import plugin_pool

from . import models


class HoverAnimationPlugin(plugin_base.CMSPluginBase):
    """
    This plugin displays an on-hover animation.
    """

    module = 'wlan slovenija'
    model = models.HoverAnimation
    name = _("Hover animation")
    render_template = "hoveranimation/animation.html"

    def render(self, context, instance, placeholder):
        context.update({
            'object': instance,
            'placeholder': placeholder,
        })
        return context


plugin_pool.register_plugin(HoverAnimationPlugin)
Example #53
0
    def get_render_template(self, context, instance, placeholder):
        # returns the first template that exists, falling back to bundled template
        return select_template([
            instance.form_template, settings.DJANGOCMS_FORMS_DEFAULT_TEMPLATE,
            'djangocms_forms/form_template/default.html'
        ])

    def render(self, context, instance, placeholder):
        context = super(FormPlugin, self).render(context, instance,
                                                 placeholder)
        request = context['request']

        form = FormBuilder(initial={'referrer': request.path_info},
                           form_definition=instance,
                           label_suffix='',
                           auto_id='%s')

        redirect_delay = instance.redirect_delay or \
            getattr(settings, 'DJANGOCMS_FORMS_REDIRECT_DELAY', 1000)

        context.update({
            'form': form,
            'recaptcha_site_key':
            settings.DJANGOCMS_FORMS_RECAPTCHA_PUBLIC_KEY,
            'redirect_delay': redirect_delay
        })
        return context


plugin_pool.register_plugin(FormPlugin)
Example #54
0
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from .models import ResponsiveWrapperPlugin


class ResponsiveWrapperCMSPlugin(CMSPluginBase):
    model = ResponsiveWrapperPlugin
    name = _("Responsive Wrapper")
    render_template = 'aldryn_responsive/plugins/wrapper.html'
    allow_children = True

    def render(self, context, instance, placeholder):
        context.update({'instance': instance})
        return context


plugin_pool.register_plugin(ResponsiveWrapperCMSPlugin)
Example #55
0
except ImportError:
    pass
else:
    # Don't like doing this. But we shouldn't force captcha.
    class CaptchaField(Field):
        name = _('Captcha Field')
        form = CaptchaFieldForm
        form_field = CaptchaField
        form_field_widget = CaptchaTextInput
        form_field_enabled_options = ['label', 'error_messages']

        def serialize_field(self, *args, **kwargs):
            # None means don't serialize me
            return None

    plugin_pool.register_plugin(CaptchaField)


class SubmitButton(FormElement):
    render_template = 'aldryn_forms/submit_button.html'
    name = _('Submit Button')
    model = models.FormButtonPlugin


plugin_pool.register_plugin(BooleanField)
plugin_pool.register_plugin(EmailField)
plugin_pool.register_plugin(FileField)
plugin_pool.register_plugin(ImageField)
plugin_pool.register_plugin(Fieldset)
plugin_pool.register_plugin(FormPlugin)
plugin_pool.register_plugin(MultipleSelectField)
Example #56
0
        initial='default',
        help_text=_("Render an alternative Breadcrumb"),
    )

    @classmethod
    def get_identifier(cls, instance):
        render_type = instance.glossary.get('render_type')
        return mark_safe(dict(cls.CHOICES).get(render_type, ''))

    def get_render_template(self, context, instance, placeholder):
        render_type = instance.glossary.get('render_type')
        try:
            return select_template([
                '{}/breadcrumb/{}.html'.format(shop_settings.APP_LABEL,
                                               render_type),
                'shop/breadcrumb/{}.html'.format(render_type),
            ])
        except TemplateDoesNotExist:
            return Template('<!-- empty breadcrumb -->')

    def get_use_cache(self, context, instance, placeholder):
        try:
            app = apphook_pool.get_apphook(instance.page.application_urls)
            return app.cache_placeholders
        except (AttributeError, ImproperlyConfigured):
            return super(BreadcrumbPlugin,
                         self).get_use_cache(context, instance, placeholder)


plugin_pool.register_plugin(BreadcrumbPlugin)
    def render(self, context, instance, placeholder):
        request = context['request']
        
        if instance and instance.template:
            self.render_template = instance.template
        
        if request.method == "POST":
            form = ContactFormPlus(contactFormInstance=instance, request=request, data=request.POST)
            if form.is_valid():
                form.send(instance.recipient_email, request)
                context.update({
                    'contact': instance,
                })
                return context
            else:
                context.update({
                    'contact': instance,
                    'form': form,
                        
                })
        else:
            form = ContactFormPlus(contactFormInstance=instance, request=request) 
            context.update({
                    'contact': instance,
                    'form': form,
            })
        return context


plugin_pool.register_plugin(CMSContactPlusPlugin)
Example #58
0
    fieldsets = [
        (None, {
            'fields': ('inner_type', )
        }),
        (_('Advanced settings'), {
            'classes': ('collapse', ),
            'fields': (
                'tag_type',
                'attributes',
            )
        }),
    ]

    def render(self, context, instance, placeholder):
        link_classes = []
        if instance.inner_type:
            link_classes.append(instance.inner_type)

        classes = concat_classes(link_classes + [
            instance.attributes.get('class'),
        ])
        instance.attributes['class'] = classes

        return super(Bootstrap4CardInnerPlugin,
                     self).render(context, instance, placeholder)


plugin_pool.register_plugin(Bootstrap4CardPlugin)
plugin_pool.register_plugin(Bootstrap4CardInnerPlugin)
Example #59
0
        pass

    def __iter__(self):
        yield self.__class__
        yield "{{baz}}"


class NotIndexedPlugin(CMSPluginBase):
    model = CMSPlugin
    plugin_content = 'rendered plugin content'
    render_template = Template(plugin_content)

    def render(self, context, instance, placeholder):
        return context

plugin_pool.register_plugin(NotIndexedPlugin)


class HiddenPlugin(CMSPluginBase):
    model = CMSPlugin
    plugin_content = 'never search for this content'
    render_template = Template(plugin_content)

    def render(self, context, instance, placeholder):
        return context

plugin_pool.register_plugin(HiddenPlugin)


class BaseTestCase(TestCase):
    def setUp(self):
Example #60
0
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from . import models


class RevDescUnalteredP(CMSPluginBase):
    model = models.UnalteredPM
    render_template = 'cms/content.html'


plugin_pool.register_plugin(RevDescUnalteredP)


class RevDescNoRelNmeP(CMSPluginBase):
    model = models.NoRelNmePM
    render_template = 'cms/content.html'


plugin_pool.register_plugin(RevDescNoRelNmeP)


class RevDescNoRelQNmeP(CMSPluginBase):
    model = models.NoRelQNmePM
    render_template = 'cms/content.html'


plugin_pool.register_plugin(RevDescNoRelQNmeP)


class RevDescCustomRelQNmeP(CMSPluginBase):