Esempio n. 1
0
    def render(self, **kwargs):
        context = kwargs.pop('context', None)
        name = 'content/template/%s' % self.filename

        for loader in self.template_loaders:
            try:
                template, display_name = loader.load_template(name)
            except TemplateDoesNotExist:
                continue

            if not hasattr(template, 'render'):
                template = Template(template, name=name)

            if context:
                ctx = context
                ctx.update(dict(content=self, **kwargs))
            else:
                ctx = Context(dict(content=self, **kwargs))

            result = template.render(ctx)

            if context:
                context.pop()

            return result

        return u''  # Fail?
Esempio n. 2
0
    def render(self, **kwargs):
        context = kwargs.pop('context', None)
        name = 'content/template/%s' % self.filename

        for loader in self.template_loaders:
            try:
                template, display_name = loader.load_template(name)
            except TemplateDoesNotExist:
                continue

            if not hasattr(template, 'render'):
                template = Template(template, name=name)

            if context:
                ctx = context
                ctx.update(dict(content=self, **kwargs))
            else:
                ctx = Context(dict(content=self, **kwargs))

            result = template.render(ctx)

            if context:
                context.pop()

            return result

        return u'' # Fail?
Esempio n. 3
0
 def content(self):
     c = Context({
         'query_groups': self.query_groups,
         'unique_count': self.unique_count
     })
     t = Template(template_string, name='SQLUniqueDebugPanel template')
     
     return t.render(c)
Esempio n. 4
0
 def test_loads_without_error(self):
     '''Ensure that the templatetags lib loads without issue'''
     # This test is the first port of call to ensure there's no silly errors
     # in the templatetags lib that might prevent it loading (syntax errors,
     # I'm looking at you!)
     template = Template('''{% load admin_links %}''')
     context = Context({})
     result = template.render(context)
     # Should be blank, because we're not doing anything.
     self.assertEqual(result, u'')
Esempio n. 5
0
    def test_can_override_django_h5bp_js_block(self):
        context = Context({})
        self.template_txt += """

        {% block django-h5bp-js %}<div>NO-BOCK</div>{% endblock %}
        """
        template = Template(self.template_txt)
        rendered = template.render(context)
        self.assertInHTML(
            """<div>NO-BOCK</div>""",
            rendered,
            msg_prefix="Could not override django-h5bp-js block. "
        )
Esempio n. 6
0
    def _write_style(self, book):
        """Creates style file.

        Style file will include default styling, theme styling and custom styling
        provided by the user.

        Created style file will be used by booktype2mpdf.php script
        to create final PDF file.

        :Args:
          - book: EPUB Book object
        """

        if 'settings' not in self.config:
            return

        css_style = create_default_style(self.config, self.name,
                                         self.get_extra_style(book))
        theme_style = u''

        if self.theme_name != '':
            theme_style = read_theme_style(self.theme_name, self.name)

            try:
                if self.theme_name == 'custom':
                    custom = self.config['theme'].pop('custom', '{}')
                    custom = json.loads(custom.encode('utf-8'))
                    self.config.update(custom)

                tmpl = Template(theme_style)
                ctx = Context(self.config)
                _style = tmpl.render(ctx)
                theme_style = _style
            except:
                logger.exception("Writing styles failed for `%s` theme." %
                                 self.theme_name)

        custom_style = self.config.get('settings', {}).get('styling', u'')

        f = codecs.open('{}/style.css'.format(self.sandbox_path), 'wt', 'utf8')
        f.write(css_style)
        f.write(theme_style)
        f.write(custom_style)
        f.close()
Esempio n. 7
0
    def _write_style(self, book):
        """Creates style file.

        Style file will include default styling, theme styling and custom styling
        provided by the user.

        Created style file will be used by booktype2mpdf.php script
        to create final PDF file.

        :Args:
          - book: EPUB Book object
        """

        if 'settings' not in self.config:
            return

        css_style = create_default_style(self.config, self.name, self.get_extra_style(book))
        theme_style = u''

        if self.theme_name != '':
            theme_style = read_theme_style(self.theme_name, self.name)

            try:
                if self.theme_name == 'custom':
                    custom = self.config['theme'].pop('custom', '{}')
                    custom = json.loads(custom.encode('utf-8'))
                    self.config.update(custom)

                tmpl = Template(theme_style)
                ctx = Context(self.config)
                _style = tmpl.render(ctx)
                theme_style = _style
            except:
                logger.exception("Writing styles failed for `%s` theme." % self.theme_name)

        custom_style = self.config.get('settings', {}).get('styling', u'')

        f = codecs.open('{}/style.css'.format(self.sandbox_path), 'wt', 'utf8')
        f.write(css_style)
        f.write(theme_style)
        f.write(custom_style)
        f.close()
Esempio n. 8
0
def _handle_batch(election, polls, vars, auto_link=False):
    errors = []
    existing = election.polls.filter()
    get_poll = lambda ref: election.polls.filter(linked_ref=ref).count() \
        and election.polls.get(linked_ref=ref)

    # Import/update/remove polls
    polls_form_data = {}
    refs = []

    byref = {}
    for p in polls:
        ref = p.get('ref')
        assert ref
        assert ref not in byref.keys()
        byref[ref] = p
    existing_refs = []
    new_refs = []

    polls_form_data = {}
    i = 0
    initial_count = 0

    refs = [p.get('ref') for p in polls]

    # update existing
    for poll in existing:
        fields = {}
        prefix = "form-%d-" % i
        add_field = lambda name, val: fields.update({'' + prefix + name: val})
        poll_data = byref.get(poll.linked_ref)
        if not poll_data:
            poll.delete()
            poll.logger.info("Poll deleted")
            continue
        add_field('name', poll_data.get('name'))
        add_field('id', poll.pk)
        polls_form_data.update(fields)
        existing_refs.append(poll.linked_ref)
        initial_count += 1
        i = i + 1

    # append new takes place in higher indexes
    for ref, poll_data in byref.iteritems():
        if ref in existing_refs:
            continue
        fields = {}
        add_field = lambda name, val: fields.update({'' + prefix + name: val})
        prefix = "form-%d-" % i
        add_field('name', poll_data.get('name').strip())
        add_field('id', None)
        polls_form_data.update(fields)
        new_refs.append(ref)
        i = i + 1

    polls_form_data.update({
        'form-INITIAL_FORMS': initial_count,
        'form-MAX_NUM_FORMS': 200,
        'form-TOTAL_FORMS': len(polls)
    })

    polls_formset = modelformset_factory(Poll,
                                         PollForm,
                                         extra=10,
                                         max_num=200,
                                         can_delete=False,
                                         formset=PollFormSet)

    form = polls_formset(polls_form_data,
                         queryset=election.polls.filter(),
                         election=election)
    form.save(election)

    for i, poll in enumerate(election.polls.filter()):
        if not poll.linked_ref:
            ref = new_refs.pop(0)
        else:
            ref = poll.linked_ref
        poll_data = byref.get(ref)
        link_id = poll_data.get('linkd_id', '')
        if not link_id and auto_link:
            link_id = election.uuid

        if not poll.linked_ref:
            poll.logger.info("Poll created")
        poll.link_id = link_id or ''
        poll.linked_ref = ref
        poll.index = refs.index(ref) + 1
        poll.save()

    # handle polls questions
    for i, poll_data in enumerate(polls):
        module = election.get_module()
        ref = poll_data.get('ref')
        questions = poll_data.get('questions')

        poll = election.polls.get(linked_ref=ref)
        formset = module.questions_formset()

        questions_form_data = {}
        poll.questions = None
        poll.questions_data = None
        poll.save()

        for qi, q in enumerate(questions):
            fields = {}
            prefix = 'form-%d-' % qi
            add_field = lambda name, val: fields.update(
                {'' + prefix + name: val})
            question = q.get('question')
            tpl = Template(question)
            context = Context(vars)
            question = tpl.render(context)
            qanswers = q.get('answers')
            min_choices = q.get('min', 1)
            max_choices = q.get('max', 1)

            add_field('choice_type', 'choice')
            add_field('max_answers', max_choices)
            add_field('min_answers', min_choices)
            add_field('question', question.strip())
            add_field('ORDER', '')

            if isinstance(qanswers, basestring):
                _orig = qanswers
                qanswers = vars.get(qanswers)
                if qanswers is None:
                    raise Exception("Invalid var name '%s'" % _orig)

            for ai, answer in enumerate(qanswers):
                add_field('answer_%d' % ai, answer)
            questions_form_data.update(fields)

        questions_form_data.update({
            'form-INITIAL_FORMS': 1,
            'form-MAX_NUM_FORMS': 200,
            'form-TOTAL_FORMS': len(questions)
        })
        form = formset(questions_form_data)
        if form.is_valid():
            qdata = module.extract_question_data(form.cleaned_data)
            poll.questions_data = qdata
            poll.update_answers()
            poll.logger.info("Poll questions updated")
            poll.save()
            try:
                poll.zeus._validate_candidates()
            except Exception, e:
                raise Exception((poll.name, unicode(e)))
        else:
            for f in form:
                for field in f:
                    for error in field.errors:
                        errors.append(error)
Esempio n. 9
0
def _handle_batch(election, polls, vars, auto_link=False):
    errors = []
    existing = election.polls.filter()
    get_poll = lambda ref: election.polls.filter(linked_ref=ref).count() \
        and election.polls.get(linked_ref=ref)

    # Import/update/remove polls
    polls_form_data = {}
    refs = []

    byref = {}
    for p in polls:
        ref = p.get('ref')
        assert ref
        assert ref not in byref.keys()
        byref[ref] = p
    existing_refs = []
    new_refs = []

    polls_form_data = {}
    i = 0
    initial_count = 0

    refs = [p.get('ref') for p in polls]

    # update existing
    for poll in existing:
        fields = {}
        prefix = "form-%d-" % i
        add_field = lambda name, val: fields.update({''+prefix+name: val})
        poll_data = byref.get(poll.linked_ref)
        if not poll_data:
            poll.delete()
            poll.logger.info("Poll deleted")
            continue
        add_field('name', poll_data.get('name'))
        add_field('id', poll.pk)
        polls_form_data.update(fields)
        existing_refs.append(poll.linked_ref)
        initial_count += 1
        i = i + 1

    # append new takes place in higher indexes
    for ref, poll_data in byref.iteritems():
        if ref in existing_refs:
            continue
        fields = {}
        add_field = lambda name, val: fields.update({''+prefix+name: val})
        prefix = "form-%d-" % i
        add_field('name', poll_data.get('name').strip())
        add_field('id', None)
        polls_form_data.update(fields)
        new_refs.append(ref)
        i = i + 1
    
    polls_form_data.update({
        'form-INITIAL_FORMS': initial_count,
        'form-MAX_NUM_FORMS': 200,
        'form-TOTAL_FORMS': len(polls)
    })
    
    polls_formset = modelformset_factory(Poll, PollForm, extra=10,
                                         max_num=200, can_delete=False,
                                         formset=PollFormSet)

    form = polls_formset(polls_form_data,
                         queryset=election.polls.filter(),
                         election=election)
    form.save(election)

    for i, poll in enumerate(election.polls.filter()):
        if not poll.linked_ref:
            ref = new_refs.pop(0)
        else:
            ref = poll.linked_ref
        poll_data = byref.get(ref)
        link_id = poll_data.get('linkd_id', '')
        if not link_id and auto_link:
            link_id = election.uuid

        if not poll.linked_ref:
            poll.logger.info("Poll created")
        poll.link_id = link_id or ''
        poll.linked_ref = ref
        poll.index = refs.index(ref) + 1
        poll.save()

    # handle polls questions
    for i, poll_data in enumerate(polls):
        module = election.get_module()
        ref = poll_data.get('ref')
        questions = poll_data.get('questions')

        poll = election.polls.get(linked_ref=ref)
        formset = module.questions_formset()

        questions_form_data = {}
        poll.questions = None
        poll.questions_data = None
        poll.save()

        for qi, q in enumerate(questions):
            fields = {}
            prefix = 'form-%d-' % qi
            add_field = lambda name, val: fields.update({''+prefix+name: val})
            question = q.get('question')
            tpl = Template(question)
            context = Context(vars)
            question = tpl.render(context)
            qanswers = q.get('answers')
            min_choices = q.get('min', 1)
            max_choices = q.get('max', 1)

            add_field('choice_type', 'choice')
            add_field('max_answers', max_choices)
            add_field('min_answers', min_choices)
            add_field('question', question.strip())
            add_field('ORDER', '')

            if isinstance(qanswers, basestring):
                _orig = qanswers
                qanswers = vars.get(qanswers)
                if qanswers is None:
                    raise Exception("Invalid var name '%s'" % _orig)

            for ai, answer in enumerate(qanswers):
                add_field('answer_%d' % ai, answer)
            questions_form_data.update(fields)

        questions_form_data.update({
            'form-INITIAL_FORMS': 1,
            'form-MAX_NUM_FORMS': 200,
            'form-TOTAL_FORMS': len(questions)
        })
        form = formset(questions_form_data)
        if form.is_valid():
            qdata = module.extract_question_data(form.cleaned_data)
            poll.questions_data = qdata
            poll.update_answers()
            poll.logger.info("Poll questions updated")
            poll.save()
            try:
                poll.zeus._validate_candidates()
            except Exception, e:
                raise Exception((poll.name, unicode(e)))
        else:
            for f in form:
                for field in f:
                    for error in field.errors:
                        errors.append(error)
Esempio n. 10
0
    def _add_css_styles(self, epub_book):
        """Adds default css styles and custom css text if exists in config"""

        book_css = []

        try:
            content = render_to_string(
                'themes/style_{}.css'.format(self.name),
                {'dir': self.direction}
            )

            item = ebooklib.epub.EpubItem(
                uid='default.css',
                content=content,
                file_name='{}/{}'.format(STYLES_DIR, 'default.css'),
                media_type='text/css'
            )

            epub_book.add_item(item)
            book_css.append('default.css')
        except:
            pass

        if self.theme_name:
            content = read_theme_style(self.theme_name, self.name)

            if self.theme_name == 'custom':
                try:
                    data = json.loads(self.config['theme']['custom'].encode('utf8'))

                    tmpl = Template(content)
                    ctx = Context(data)
                    content = tmpl.render(ctx)
                except:
                    logger.exception("Fails with custom theme.")

            item = ebooklib.epub.EpubItem(
                uid='theme.css',
                content=content,
                file_name='{}/{}'.format(STYLES_DIR, 'theme.css'),
                media_type='text/css'
            )

            epub_book.add_item(item)
            book_css.append('theme.css')

        # we need to add css from publishing settings screen
        settings_style = self.config.get('settings', {}).get('styling', None)

        if settings_style:
            item = ebooklib.epub.EpubItem(
                uid='custom_style.css',
                content=settings_style,
                file_name='{}/{}'.format(STYLES_DIR, 'custom_style.css'),
                media_type='text/css'
            )

            epub_book.add_item(item)
            book_css.append('custom_style.css')

        return book_css
Esempio n. 11
0
    def _add_css_styles(self, epub_book):
        """Adds default css styles and custom css text if exists in config"""

        book_css = []

        try:
            content = render_to_string(
                'themes/style_{}.css'.format(self.name),
                {'dir': self.direction}
            )

            item = ebooklib.epub.EpubItem(
                uid='default.css',
                content=content,
                file_name='{}/{}'.format(STYLES_DIR, 'default.css'),
                media_type='text/css'
            )

            epub_book.add_item(item)
            book_css.append('default.css')
        except:
            pass

        if self.theme_name:
            content = read_theme_style(self.theme_name, self.name)

            if self.theme_name == 'custom':
                try:
                    data = json.loads(self.config['theme']['custom'].encode('utf8'))

                    tmpl = Template(content)
                    ctx = Context(data)
                    content = tmpl.render(ctx)
                except:
                    logger.exception("Fails with custom theme.")

            item = ebooklib.epub.EpubItem(
                uid='theme.css',
                content=content,
                file_name='{}/{}'.format(STYLES_DIR, 'theme.css'),
                media_type='text/css'
            )

            epub_book.add_item(item)
            book_css.append('theme.css')

        # we need to add css from publishing settings screen
        settings_style = self.config.get('settings', {}).get('styling', None)

        if settings_style:
            item = ebooklib.epub.EpubItem(
                uid='custom_style.css',
                content=settings_style,
                file_name='{}/{}'.format(STYLES_DIR, 'custom_style.css'),
                media_type='text/css'
            )

            epub_book.add_item(item)
            book_css.append('custom_style.css')

        return book_css