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?
    def test_tag_follow_label(self):
        src = '{% load activity_tags %}'\
            '{% follow_label other_user yup nope %}'

        # Anonymous.
        output = Template(src).render(Context({'other_user': self.user1}))
        self.assertEqual(output, 'nope')

        output = Template(src).render(
            Context({
                'user': AnonymousUser(),
                'other_user': self.user1
            }))
        self.assertEqual(output, 'nope')

        # Non follower (user2 does not follow user1).
        output = Template(src).render(
            Context({
                'user': self.user2,
                'other_user': self.user1
            }))
        self.assertEqual(output, 'nope')

        # Follower (user1 follows user2).
        output = Template(src).render(
            Context({
                'user': self.user1,
                'other_user': self.user2
            }))
        self.assertEqual(output, 'yup')
Esempio n. 3
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. 4
0
 def test_is_following_filter(self):
     src = '{% load activity_tags %}{% if user|is_following:group %}yup{% endif %}'
     self.assertEqual(Template(src).render(Context({
         'user': self.user2, 'group': self.group
     })), u'yup')
     self.assertEqual(Template(src).render(Context({
         'user': self.user1, 'group': self.group
     })), u'')
Esempio n. 5
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. 6
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. 7
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. 8
0
 def templatize(self, text, context):
     """
     Helper function that pushes the text through the django templating engine.
     Keep in mind that it does *not* escape text, which is good!
     """
     return Template("{% autoescape off %}" + text +
                     "{% endautoescape %}").render(context)
Esempio n. 9
0
def render_archivedpage(request, url):
    """
    Render a requested ArchivedPage URL
    """
    try:
        apage = get_object_or_404(ArchivedPage, url__exact="/%s" % url)
    except Http404:
        if not url.endswith('/') and settings.APPEND_SLASH:
            apage = get_object_or_404(ArchivedPage, url__exact="/%s/" % url)
            return HttpResponsePermanentRedirect('%s/' % request.path)
        else:
            raise
    if apage.template_name:
        templates = [apage.template_name, DEFAULT_TEMPLATE]
    else:
        templates = get_templates_from_path(url)
        templates.append(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    apage.title = mark_safe(apage.title)
    apage.content = mark_safe(Template(apage.content).render(Context({})))

    return render_to_response(templates, {'object': apage},
                              RequestContext(request))
Esempio n. 10
0
	def send(self, network, test_user = None):
		subject_template = Template(self.subject_template)
		header_template = Template(self.header_template)
		footer_template = Template(self.footer_template)
		logger = logging.getLogger()
		emails = []
		
		context = {
			'network': network,
			'MEDIA_URL': getattr(settings, 'MEDIA_URL', '/media/'),
		}
		
		if not test_user:
			if self.sent:
				raise Exception('Message already sent')
			
			if self.recipients.filter(test = False).count() > 0:
				raise Exception('Message already has recipients')
			
			for user in self.filter_users():
				self.recipients.create(user = user)
			
			for user in self.recipients.filter(test = False):
				emails.append(
					user.prepare_email(
						context, subject_template, header_template, footer_template
					)
				)
			
			self.sent = datetime.now()
			super(Message, self).save()
		else:
			user = self.recipients.create(
				user = test_user, test = True
			)
			
			emails.append(
				user.prepare_email(
					context, subject_template, header_template, footer_template
				)
			)
		
		connection = get_connection()
		connection.send_messages(emails)
		logger.info('Sent email to %d recipients' % len(emails))
Esempio n. 11
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. 12
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. 13
0
 def test_tag_follow_url(self):
     src = '{% load activity_tags %}{% follow_url user %}'
     output = Template(src).render(Context({'user': self.user1}))
     ct = ContentType.objects.get_for_model(User)
     self.assertEqual(output, '/follow/%s/%s/' % (ct.pk, self.user1.pk))
Esempio n. 14
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. 15
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. 16
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. 17
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. 18
0
 def test_compressor_can_compile_scss_from_style_tag(self):
     actual = Template(IMPORT_APP2_STYLE_TAG).render(Context())
     self.assertIn('4b368862ec8c.css', actual)
Esempio n. 19
0
 def test_follow_templates(self):
     ct = ContentType.objects.get_for_model(User)
     src = '{% load activity_tags %}{% activity_follow_url user %}{% activity_follow_label user yup nope %}'
     self.assert_(
         Template(src).render(Context({'user': self.user1})).endswith(
             '/%s/%s/nope' % (ct.id, self.user1.id)))
Esempio n. 20
0
	def prepare_email(self, base_context, subject_template, header_template, footer_template):
		try:
			profile = self.user.get_profile()
		except Profile.DoesNotExist:
			profile = None
		
		context = Context(
			{
				'first_name': self.user.first_name,
				'last_name': self.user.last_name,
				'username': self.user.username,
				'email': self.user.email,
				'is_staff': self.user.is_staff,
				'is_active': self.user.is_active,
				'is_superuser': self.user.is_superuser,
				'last_login': self.user.last_login,
				'date_joined': self.user.date_joined,
				'profile': profile
			}
		)
		
		subject = subject_template.render(context)
		sections = []
		
		for section in self.message.sections.all():
			sections.append(
				{
					'title': Template(section.title_template).render(context),
					'body': Template(section.body_template).render(context),
					'image': get_thumbnail(section.image, '150x150', crop = 'center')
				}
			)
		
		base_context['unsubscribe_url'] = 'http://%s%s' % (
			base_context['network'].domain,
			reverse('mail_unsubscribe', args = [self.guid])
		)
		
		header = header_template.render(context)
		footer = footer_template.render(context)
		
		base_context['body'] = render_to_string('email/sections.inc.txt',
			{
				'header': header,
				'sections': sections,
				'footer': footer
			}
		)
		
		email = EmailMultiAlternatives(
			subject,
			render_to_string('email/base.txt', base_context),
			'Meegloo mail <%s>' % FROM_EMAIL,
			[
				self.user.first_name and (
					'%s %s <%s>' % (self.user.first_name, self.user.last_name, self.user.email)
				) or self.user.email
			]
		)
		
		base_context['body'] = render_to_string('email/sections.inc.html',
			{
				'header': header,
				'sections': sections,
				'footer': footer
			}
		)
		
		email.attach_alternative(
			render_to_string('email/base.html', base_context),
			'text/html'
		)
		
		return email
Esempio n. 21
0
def render(src, **ctx):
    return Template('{% load activity_tags %}' + src).render(Context(ctx))
Esempio n. 22
0
 def test_compressor_can_compile_scss(self):
     actual = Template(APP2_LINK_TAG).render(Context())
     # 4b368862ec8c is the cache key that compressor gives to the compiled
     # version of app2.scss.
     self.assertIn('4b368862ec8c.css', actual)