Ejemplo n.º 1
0
    def test_submit_cancel_form_helper(self):
        """Test custom crispy forms layout helper"""
        template = Engine().get_default().from_string("""
            {% load crispy_forms_tags %}
            {% crispy form %}
        """)

        test_form = SampleForm()
        test_form.helper = SubmitCancelFormHelper(test_form)

        c = Context({'form': test_form})

        html = template.render(c)
        self.assertEqual(html.count('role="button"'), 1)
        self.assertEqual(html.count('href="#"'), 1)
        self.assertEqual(html.count('Cancel'), 1)
        self.assertEqual(html.count('Submit'), 1)

        test_form = SampleForm()
        test_form.helper = SubmitCancelFormHelper(test_form,
                                                  cancel_href="/some/url/")

        c = Context({'form': test_form})

        html = template.render(c)
        self.assertEqual(html.count('href="/some/url/'), 1)
Ejemplo n.º 2
0
class DjangoRenderer(TemplateRenderer):
    """
    Renders Django templates.

    :param engine: a Django template engine object or keyword arguments for its constructor
    :param package_paths: if given, looks up the directories containing the given package and fills
        in or extends the ``dirs`` argument for :class:`~django.template.Engine`. The value will be
        interpreted by :func:`~asphalt.templating.util.package_to_directory`.
    """

    __slots__ = 'engine'

    def __init__(self, engine: Union[Engine, Dict[str, Any]] = None,
                 package_paths: Iterable[str] = ()):
        assert check_argument_types()
        self.engine = engine or {}
        if isinstance(self.engine, dict):
            self.engine.setdefault('dirs', []).extend(package_to_directory(pkg) for
                                                      pkg in package_paths)
            self.engine = Engine(**self.engine)

    def render(self, template: str, **vars) -> str:
        template = self.engine.get_template(template)
        context = Context(vars)
        return template.render(context)

    def render_string(self, source: str, **vars) -> str:
        template = self.engine.from_string(source)
        context = Context(vars)
        return template.render(context)
Ejemplo n.º 3
0
    def test_extend_cached(self):
        engine = Engine(
            dirs=[
                os.path.join(RECURSIVE, 'fs'),
                os.path.join(RECURSIVE, 'fs2'),
                os.path.join(RECURSIVE, 'fs3'),
            ],
            loaders=[
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                ]),
            ],
        )
        template = engine.get_template('recursive.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'fs3/recursive fs2/recursive fs/recursive')

        cache = engine.template_loaders[0].get_template_cache
        self.assertEqual(len(cache), 3)
        expected_path = os.path.join('fs', 'recursive.html')
        self.assertTrue(cache['recursive.html'].origin.name.endswith(expected_path))

        # Render another path that uses the same templates from the cache
        template = engine.get_template('other-recursive.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'fs3/recursive fs2/recursive fs/recursive')

        # Template objects should not be duplicated.
        self.assertEqual(len(cache), 4)
        expected_path = os.path.join('fs', 'other-recursive.html')
        self.assertTrue(cache['other-recursive.html'].origin.name.endswith(expected_path))
Ejemplo n.º 4
0
def create_site(name, directory=SITE_DIR, templates_dir=TEMPLATES_DIR, static_dir=RESOURCES_DIR):

    if not directory:
        sys.stderr.write("Please provide a site name, e.g. %s <site_name>\n\n" % NAME)
        sys.exit(1)

    sys.stdout.write("\tCopying site templates to %s\n" % directory)

    # Generate manage.py
    from django.template import Engine, Context

    engine = Engine()
    f = open(os.path.join(os.path.dirname(templates_dir), "manage.txt"))
    template = engine.from_string(f.read())
    f.close()
    managepy_file_contents = template.render(Context({"site_name": name}))
    managepy_file = open(os.path.join(BASE_DIR, "manage.py"), "w+")
    managepy_file.write(managepy_file_contents)
    managepy_file.close()
    os.chmod(os.path.join(BASE_DIR, "manage.py"), 0755)

    # copy template framework into site directory
    shutil.copytree("%s/" % templates_dir, directory, ignore=shutil.ignore_patterns(".svn"))

    site_resources = "%s/%s" % (static_dir, name)

    # make static dirs
    for static_dir in STATIC_DIRS:
        try:
            os.makedirs("%s/%s" % (site_resources, static_dir))
            sys.stdout.write("\tCreated %s in %s\n" % (static_dir, site_resources))
        except:
            pass
Ejemplo n.º 5
0
 def test_correct_exception_index(self):
     tests = [
         ('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}', (38, 56)),
         (
             '{% load bad_tag %}{% for i in range %}{% for j in range %}'
             '{% badsimpletag %}{% endfor %}{% endfor %}',
             (58, 76)
         ),
         (
             '{% load bad_tag %}{% for i in range %}{% badsimpletag %}'
             '{% for j in range %}Hello{% endfor %}{% endfor %}',
             (38, 56)
         ),
         (
             '{% load bad_tag %}{% for i in range %}{% for j in five %}'
             '{% badsimpletag %}{% endfor %}{% endfor %}',
             (38, 57)
         ),
         ('{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}', (18, 37)),
     ]
     context = Context({
         'range': range(5),
         'five': 5,
     })
     engine = Engine(debug=True, libraries={'bad_tag': 'template_tests.templatetags.bad_tag'})
     for source, expected_error_source_index in tests:
         template = engine.from_string(source)
         try:
             template.render(context)
         except (RuntimeError, TypeError) as e:
             debug = e.template_debug
             self.assertEqual((debug['start'], debug['end']), expected_error_source_index)
Ejemplo n.º 6
0
def render_to_string(template_name, context):
    """
    The same as the Django one but this only searches for templates in the './templates' folder.
    """
    template_engine = Engine(dirs=[os.path.join(BASE_DIR, 'templates')])
    template = template_engine.get_template(template_name)
    return template.render(Context(context))
Ejemplo n.º 7
0
def csrf_failure(request, reason=""):
    """
    Default view used when request fails CSRF protection
    """
    from django.middleware.csrf import REASON_NO_REFERER, REASON_NO_CSRF_COOKIE
    t = Engine().from_string(CSRF_FAILURE_TEMPLATE)
    c = Context({
        'title': _("Forbidden"),
        'main': _("CSRF verification failed. Request aborted."),
        'reason': reason,
        'no_referer': reason == REASON_NO_REFERER,
        'no_referer1': _(
            "You are seeing this message because this HTTPS site requires a "
            "'Referer header' to be sent by your Web browser, but none was "
            "sent. This header is required for security reasons, to ensure "
            "that your browser is not being hijacked by third parties."),
        'no_referer2': _(
            "If you have configured your browser to disable 'Referer' headers, "
            "please re-enable them, at least for this site, or for HTTPS "
            "connections, or for 'same-origin' requests."),
        'no_cookie': reason == REASON_NO_CSRF_COOKIE,
        'no_cookie1': _(
            "You are seeing this message because this site requires a CSRF "
            "cookie when submitting forms. This cookie is required for "
            "security reasons, to ensure that your browser is not being "
            "hijacked by third parties."),
        'no_cookie2': _(
            "If you have configured your browser to disable cookies, please "
            "re-enable them, at least for this site, or for 'same-origin' "
            "requests."),
        'DEBUG': settings.DEBUG,
        'docs_version': get_docs_version(),
        'more': _("More information is available with DEBUG=True."),
    })
    return HttpResponseForbidden(t.render(c), content_type='text/html')
Ejemplo n.º 8
0
 def test_filter(self):
     engine = Engine(libraries=LIBRARIES)
     t = engine.from_string("{% load custom %}{{ string|trim:5 }}")
     self.assertEqual(
         t.render(Context({"string": "abcdefghijklmnopqrstuvwxyz"})),
         "abcde"
     )
Ejemplo n.º 9
0
 def test_extend_recursive(self):
     engine = Engine(
         dirs=[os.path.join(RECURSIVE, "fs"), os.path.join(RECURSIVE, "fs2"), os.path.join(RECURSIVE, "fs3")]
     )
     template = engine.get_template("recursive.html")
     output = template.render(Context({}))
     self.assertEqual(output.strip(), "fs3/recursive fs2/recursive fs/recursive")
Ejemplo n.º 10
0
 def get_mocked_html_response(self, template_name, variables={}):
     """
     Returns the 'template_name' with the 'variables' as a resolved string.
     """
     template_engine = Engine(dirs=[os.path.join(self.BASE_DIR, 'responses')])
     template = template_engine.get_template(template_name)
     return template.render(Context(variables))
Ejemplo n.º 11
0
 def test_unknown_block_tag(self):
     engine = Engine()
     msg = (
         "Invalid block tag on line 1: 'foobar'. Did you forget to "
         "register or load this tag?"
     )
     with self.assertRaisesMessage(TemplateSyntaxError, msg):
         engine.from_string("lala{% foobar %}")
Ejemplo n.º 12
0
 def test_debug_tag_non_ascii(self):
     """
     #23060 -- Test non-ASCII model representation in debug output.
     """
     group = Group(name="清風")
     c1 = Context({"objs": [group]})
     t1 = Engine().from_string('{% debug %}')
     self.assertIn("清風", t1.render(c1))
Ejemplo n.º 13
0
 def test_debug_tag_non_ascii(self):
     """
     #23060 -- Test non-ASCII model representation in debug output.
     """
     Group.objects.create(name="清風")
     c1 = Context({"objs": Group.objects.all()})
     t1 = Engine().from_string("{% debug %}")
     self.assertIn("清風", t1.render(c1))
Ejemplo n.º 14
0
 def test_super_errors(self):
     """
     #18169 -- NoReverseMatch should not be silence in block.super.
     """
     engine = Engine(app_dirs=True)
     t = engine.get_template("included_content.html")
     with self.assertRaises(urlresolvers.NoReverseMatch):
         t.render(Context())
Ejemplo n.º 15
0
 def test_include_error(self):
     engine = Engine(dirs=[RELATIVE])
     msg = (
         "The relative path '\"./../three.html\"' points outside the file "
         "hierarchy that template 'error_include.html' is in."
     )
     with self.assertRaisesMessage(TemplateSyntaxError, msg):
         engine.render_to_string('error_include.html')
Ejemplo n.º 16
0
 def test_load_working_egg(self):
     ttext = "{% load working_egg %}"
     egg_name = '%s/tagsegg.egg' % self.egg_dir
     with extend_sys_path(egg_name):
         engine = Engine(libraries={
             'working_egg': 'tagsegg.templatetags.working_egg',
         })
         engine.from_string(ttext)
Ejemplo n.º 17
0
    def _create_accessor_function(self, sql_function_name, accessor_dir):
        with open(os.path.join(accessor_dir, TEMPLATE_NAME), encoding='utf-8') as f:
            template_string = f.read()

        template = Engine().from_string(template_string)
        rendered_template = template.render({'sql_function_name': sql_function_name})

        with open(os.path.join(accessor_dir, '{}.sql'.format(sql_function_name)), 'w+', encoding='utf-8') as f:
            f.write(rendered_template)
Ejemplo n.º 18
0
 def test_include_template_argument(self):
     """
     Support any render() supporting object
     """
     engine = Engine()
     ctx = Context({"tmpl": engine.from_string("This worked!")})
     outer_tmpl = engine.from_string("{% include tmpl %}")
     output = outer_tmpl.render(ctx)
     self.assertEqual(output, "This worked!")
Ejemplo n.º 19
0
 def test_url_reverse_no_settings_module(self):
     """
     #9005 -- url tag shouldn't require settings.SETTINGS_MODULE to
     be set.
     """
     t = Engine(debug=True).from_string("{% url will_not_match %}")
     c = Context()
     with self.assertRaises(urlresolvers.NoReverseMatch):
         t.render(c)
Ejemplo n.º 20
0
    def test_load_working_egg(self):
        ttext = "{% load working_egg %}"
        egg_name = "%s/tagsegg.egg" % self.egg_dir
        with extend_sys_path(egg_name):
            engine = Engine(libraries={"working_egg": "tagsegg.templatetags.working_egg"})
            engine.from_string(ttext)

        with six.assertRaisesRegex(self, InvalidTemplateLibrary, msg):
            Engine(libraries={"broken_tag": "template_tests.broken_tag"})
Ejemplo n.º 21
0
 def test_extend_self_error(self):
     """
     Catch if a template extends itself and no other matching
     templates are found.
     """
     engine = Engine(dirs=[os.path.join(RECURSIVE, 'fs')])
     template = engine.get_template('self.html')
     with self.assertRaises(TemplateDoesNotExist):
         template.render(Context({}))
Ejemplo n.º 22
0
 def test_mixing_loop(self):
     engine = Engine(dirs=[RELATIVE])
     msg = (
         "The relative path '\"./dir2/../looped.html\"' was translated to "
         "template name \'dir1/looped.html\', the same template in which "
         "the tag appears."
     )
     with self.assertRaisesMessage(TemplateSyntaxError, msg):
         engine.render_to_string('dir1/looped.html')
Ejemplo n.º 23
0
 def test_compile_tag_error(self):
     """
     Errors raised while compiling nodes should include the token
     information.
     """
     engine = Engine(debug=True)
     with self.assertRaises(RuntimeError) as e:
         engine.from_string("{% load bad_tag %}{% badtag %}")
     self.assertEqual(e.exception.template_debug["during"], "{% badtag %}")
Ejemplo n.º 24
0
 def test_extends_generic_template(self):
     """
     #24338 -- Allow extending django.template.backends.django.Template
     objects.
     """
     engine = Engine()
     parent = engine.from_string("{% block content %}parent{% endblock %}")
     child = engine.from_string("{% extends parent %}{% block content %}child{% endblock %}")
     self.assertEqual(child.render(Context({"parent": parent})), "child")
Ejemplo n.º 25
0
 def test_textnode_repr(self):
     engine = Engine()
     for temptext, reprtext in [
         ("Hello, world!", "<TextNode: 'Hello, world!'>"),
         ("One\ntwo.", "<TextNode: 'One\\ntwo.'>"),
     ]:
         template = engine.from_string(temptext)
         texts = template.nodelist.get_nodes_by_type(TextNode)
         self.assertEqual(repr(texts[0]), reprtext)
Ejemplo n.º 26
0
 def test_render_context_is_cleared(self):
     """
     #24555 -- InclusionNode should push and pop the render_context stack
     when rendering. Otherwise, leftover values such as blocks from
     extending can interfere with subsequent rendering.
     """
     engine = Engine(app_dirs=True, libraries=LIBRARIES)
     template = engine.from_string('{% load inclusion %}{% inclusion_extends1 %}{% inclusion_extends2 %}')
     self.assertEqual(template.render(Context({})).strip(), 'one\ntwo')
Ejemplo n.º 27
0
 def test_no_render_side_effect(self):
     """
     #23441 -- InclusionNode shouldn't modify its nodelist at render time.
     """
     engine = Engine(app_dirs=True, libraries=LIBRARIES)
     template = engine.from_string('{% load inclusion %}{% inclusion_no_params %}')
     count = template.nodelist.get_nodes_by_type(Node)
     template.render(Context({}))
     self.assertEqual(template.nodelist.get_nodes_by_type(Node), count)
Ejemplo n.º 28
0
 def test_extend_recursive(self):
     engine = Engine(dirs=[
         os.path.join(RECURSIVE, 'fs'),
         os.path.join(RECURSIVE, 'fs2'),
         os.path.join(RECURSIVE, 'fs3'),
     ])
     template = engine.get_template('recursive.html')
     output = template.render(Context({}))
     self.assertEqual(output.strip(), 'fs3/recursive fs2/recursive fs/recursive')
Ejemplo n.º 29
0
    def test_extend_missing(self):
        engine = Engine(dirs=[os.path.join(RECURSIVE, 'fs')])
        template = engine.get_template('extend-missing.html')
        with self.assertRaises(TemplateDoesNotExist) as e:
            template.render(Context({}))

        tried = e.exception.tried
        self.assertEqual(len(tried), 1)
        self.assertEqual(tried[0][0].template_name, 'missing.html')
Ejemplo n.º 30
0
    def test_invalid_block_suggestion(self):
        """
        #7876 -- Error messages should include the unexpected block name.
        """
        engine = Engine()

        with self.assertRaises(TemplateSyntaxError) as e:
            engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}")

        self.assertEqual(e.exception.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'")
Ejemplo n.º 31
0
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/'). It's
            quoted to prevent a content injection attack.
        exception
            The message from the exception which triggered the 404 (if one was
            supplied), or the exception class name
    """
    exception_repr = exception.__class__.__name__
    # Try to get an "interesting" exception message, if any (and not the ugly
    # Resolver404 dictionary)
    try:
        message = exception.args[0]
    except (AttributeError, IndexError):
        pass
    else:
        if isinstance(message, str):
            exception_repr = message
    context = {
        'request_path': quote(request.path),
        'exception': exception_repr,
    }
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None  # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        if template_name != ERROR_404_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested resource was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'
    return HttpResponseNotFound(body, content_type=content_type)
Ejemplo n.º 32
0
    def send_email(self):
        from .views import UUID

        messages_sent, body = None, None
        if self.is_valid() and self.order_token:

            email_address = self.cleaned_data['email_address']

            subject = 'Your Receipt for LibreShop Order %s!' % self.order_token

            try:
                # Get Order from specified token.
                order = Order.objects.get(token=self.order_token)

                # Get the latest Transaction.
                transaction = Transaction.objects.filter(order=order).latest()
            except (Order.DoesNotExist, Transaction.DoesNotExist) as e:
                pass
            else:
                # Load the default template engine.
                TemplateEngine = Engine.get_default()

                # Render a context to the template specified in `template_name`.
                template = TemplateEngine.get_template(self.template_name)
                context = Context({
                    'order': order,
                    'purchases': order.purchases.all(),
                    'transaction': transaction
                })
                body = template.render(context)

                message = EmailMessage(subject=subject,
                                       body=body,
                                       from_email=settings.DEFAULT_FROM_EMAIL,
                                       to=[email_address],
                                       bcc=[],
                                       connection=None,
                                       attachments=None,
                                       headers=None,
                                       cc=None,
                                       reply_to=None)

                messages_sent = message.send()

        if messages_sent:
            Communication.objects.create(
                order=order,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to_email=email_address,
                subject=subject,
                body=body)

        return bool(messages_sent)
Ejemplo n.º 33
0
def get_plugin_index_data(base_plugin, request):
    text_bits = []

    instance, plugin_type = base_plugin.get_plugin_instance()

    if instance is None:
        # this is an empty plugin
        return text_bits

    search_fields = getattr(instance, 'search_fields', [])

    if hasattr(instance, 'search_fulltext'):
        # check if the plugin instance has search enabled
        search_contents = instance.search_fulltext
    elif hasattr(base_plugin, 'search_fulltext'):
        # now check in the base plugin instance (CMSPlugin)
        search_contents = base_plugin.search_fulltext
    elif hasattr(plugin_type, 'search_fulltext'):
        # last check in the plugin class (CMSPluginBase)
        search_contents = plugin_type.search_fulltext
    else:
        # disabled if there's search fields defined,
        # otherwise it's enabled.
        search_contents = not bool(search_fields)

    if search_contents:
        context = RequestContext(request)

        if not DJANGO_1_7:
            from django.template import Engine
            # On Django <= 1.7, the RequestContext class would call
            # all context processors and update the context on initialization.
            # On Django >= 1.8 the logic to update the context
            # from context processors is now tied to the bind_template
            # context manager.
            updates = {}
            engine = Engine.get_default()

            for processor in engine.template_context_processors:
                updates.update(processor(context.request))
            context.dicts[context._processors_index] = updates

        plugin_contents = instance.render_plugin(context=context)

        if plugin_contents:
            text_bits = get_cleaned_bits(plugin_contents)
    else:
        values = (get_field_value(instance, field) for field in search_fields)

        for value in values:
            cleaned_bits = get_cleaned_bits(value or '')
            text_bits.extend(cleaned_bits)
    return text_bits
Ejemplo n.º 34
0
    def setUpClass(cls):
        super().setUpClass()
        cls.engine = Engine(loaders=[
            ('django.template.loaders.locmem.Loader', {
                'child': '{{ raises_exception }}',
            }),
        ], debug=False)

        def error_method():
            raise IndexError("some generic exception")

        cls.ctx = Context({'raises_exception': error_method})
Ejemplo n.º 35
0
    def test_extends_include_missing_cachedloader(self):
        engine = Engine(
            debug=True,
            loaders=[
                (
                    "django.template.loaders.cached.Loader",
                    [
                        "django.template.loaders.app_directories.Loader",
                    ],
                ),
            ],
        )

        template = engine.get_template("test_extends_error.html")
        with self.assertRaisesMessage(TemplateDoesNotExist, "missing.html"):
            template.render(Context())

        # Repeat to ensure it still works when loading from the cache
        template = engine.get_template("test_extends_error.html")
        with self.assertRaisesMessage(TemplateDoesNotExist, "missing.html"):
            template.render(Context())
Ejemplo n.º 36
0
    def setUpClass(cls):
        test_app_root = settings.TENANT_APPS_DIR
        settings.MULTITENANT_TEMPLATE_DIRS = [
            os.path.join(test_app_root, "tenants/%s/templates")
        ]

        cls.engine = Engine(loaders=[(
            "django_tenants.template.loaders.cached.Loader",
            ["django_tenants.template.loaders.filesystem.Loader"],
        )])

        super().setUpClass()
Ejemplo n.º 37
0
    def setUpClass(cls):
        root = os.path.dirname(os.path.abspath(__file__))
        settings.MULTITENANT_TEMPLATE_DIRS = [
            os.path.join(root, "tenants/%s/templates")
        ]

        cls.engine = Engine(loaders=[(
            "django_tenants.template.loaders.cached.Loader",
            ["django_tenants.template.loaders.filesystem.Loader"],
        )])

        super().setUpClass()
Ejemplo n.º 38
0
 def test_load_error_egg(self):
     egg_name = '%s/tagsegg.egg' % self.egg_dir
     msg = (
         "Invalid template library specified. ImportError raised when "
         "trying to load 'tagsegg.templatetags.broken_egg': cannot "
         "import name '?Xtemplate'?"
     )
     with extend_sys_path(egg_name):
         with six.assertRaisesRegex(self, InvalidTemplateLibrary, msg):
             Engine(libraries={
                 'broken_egg': 'tagsegg.templatetags.broken_egg',
             })
Ejemplo n.º 39
0
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        proposals = models.EventProposal.objects.filter(
            camp=self.camp).select_related('user', 'event')
        context['proposals'] = proposals

        engine = Engine.get_default()
        template = engine.get_template('control/proposal_overview.csv')
        csv = template.render(Context(context))
        context['csv'] = csv

        return context
Ejemplo n.º 40
0
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={
            'i18n': 'django.templatetags.i18n'
        }).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c))
Ejemplo n.º 41
0
def check_for_context_processors(app_configs, **kwargs):
    errors = []
    context_processors = Engine.get_default().context_processors
    for context_processor in REQUIRED_CONTEXT_PROCESSORS:
        if context_processor[0] not in context_processors:
            errors.append(
                Error(
                    "needs %s in TEMPLATE['OPTIONS']['context_processors']" %
                    context_processor[0],
                    id='wiki.%s' % context_processor[1],
                ))
    return errors
Ejemplo n.º 42
0
 def test_unique_history_per_loader(self):
     """
     Extending should continue even if two loaders return the same
     name for a template.
     """
     engine = Engine(loaders=[
         [
             'django.template.loaders.locmem.Loader', {
                 'base.html':
                 '{% extends "base.html" %}{% block content %}{{ block.super }} loader1{% endblock %}',
             }
         ],
         [
             'django.template.loaders.locmem.Loader', {
                 'base.html': '{% block content %}loader2{% endblock %}',
             }
         ],
     ])
     template = engine.get_template('base.html')
     output = template.render(Context({}))
     self.assertEqual(output.strip(), 'loader2 loader1')
Ejemplo n.º 43
0
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
    exception_repr = exception.__class__.__name__
    # Try to get an "interesting" exception message, if any (and not the ugly
    # Resolver404 dictionary)
    try:
        message = exception.args[0]
    except (AttributeError, IndexError):
        pass
    else:
        if isinstance(message, str):
            exception_repr = message
    context = {
        'request_path': quote(request.path),
        'exception': exception_repr,
    }
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None  # Django will use 'text/html'.
    except TemplateDoesNotExist as e:
        logger.exception(e)
        if template_name != ERROR_404_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        # Render template (even though there are no substitutions) to allow
        # inspecting the context in tests.
        template = Engine().from_string(
            ERROR_PAGE_TEMPLATE % {
                'title': 'Not Found',
                'details':
                'The requested resource was not found on this server.',
            }, )
        body = template.render(Context(context))
        content_type = 'text/html'
    except Exception as e:
        logger.exception(e)
        body = ""
        content_type = 'text/html'

    return HttpResponseNotFound(body, content_type=content_type)
Ejemplo n.º 44
0
def generate_widget_js(lang):
    code = []
    with language(lang):
        # Provide isolation
        code.append('(function (siteglobals) {\n')
        code.append('var module = {}, exports = {};\n')
        code.append('var lang = "%s";\n' % lang)

        catalog, plural = get_javascript_catalog(lang, 'djangojs', ['pretix'])
        catalog = dict(
            (k, v) for k, v in catalog.items() if k.startswith('widget\u0004'))
        template = Engine().from_string(js_catalog_template)
        context = Context({
            'catalog_str':
            indent(json.dumps(catalog, sort_keys=True, indent=2))
            if catalog else None,
            'formats_str':
            indent(json.dumps(get_formats(), sort_keys=True, indent=2)),
            'plural':
            plural,
        })
        code.append(template.render(context))

        files = [
            'vuejs/vue.js' if settings.DEBUG else 'vuejs/vue.min.js',
            'pretixpresale/js/widget/docready.js',
            'pretixpresale/js/widget/floatformat.js',
            'pretixpresale/js/widget/widget.js',
        ]
        for fname in files:
            f = finders.find(fname)
            with open(f, 'r') as fp:
                code.append(fp.read())

        if settings.DEBUG:
            code.append('})(this);\n')
        else:
            # Do not expose debugging variables
            code.append('})({});\n')
    return ''.join(code)
Ejemplo n.º 45
0
def new_product(request):
    cls_default_msgs = {
        'not_signed_in':
        'You must be signed in to list your product',
        'invalid_param':
        'Invalid parameters. \
                        Please make sure you fill in all fields',
    }

    product_form = ProductForm()
    ImageFormSet = modelformset_factory(ProductPhoto, form=ImageForm, extra=3)
    userid = request.user.id
    form = ProductForm(request.POST or None)
    formset = ImageFormSet(request.POST,
                           request.FILES,
                           queryset=ProductPhoto.objects.none())

    if request.POST:
        if request.user.is_authenticated():
            if form.is_valid() and formset.is_valid():
                product = form.save(commit=False)
                product.owner = request.user
                product.user_id = userid
                product.active = True
                product.slug = form.cleaned_data['name'].replace(" ", "")
                product.date_created = timezone.now()
                product.date_last_modified = timezone.now()
                product.save()
                for form in formset:
                    if form.cleaned_data:
                        image = form.cleaned_data['image']
                    photo = ProductPhoto(product=product, image=image)
                    photo.user_id = userid
                    photo.save()
                return render(request, "updated_product.html",
                              {"product": product})
        else:
            # Set error context
            error_msg = cls_default_msgs['not_signed_in']
            messages.add_message(request, messages.INFO, error_msg,
                                 form.errors)
            # Set template
            template = Engine.get_default().get_template('login.html')
            # Set result in RequestContext
            context = RequestContext(request)
            return HttpResponse(template.render(context))

    return render(
        request, 'products/new_product.html', {
            'form': form,
            'formset': ImageFormSet(queryset=ProductPhoto.objects.none())
        })
Ejemplo n.º 46
0
def send_templated_email(template_name,
                         context,
                         recipient_list,
                         from_email=settings.DEFAULT_FROM_EMAIL,
                         attachment_filename=None,
                         attachment_data=None):
    """
    Sends an email using a template stored in the database (based on the template name)
    Also supports attaching a file
    """
    # Get template from database, render it using the provided context
    template_engine = Engine()
    email_template = EmailTemplate.objects.get(name=template_name)
    subject_template = template_engine.from_string(email_template.subject)
    body_template = template_engine.from_string(email_template.body)
    email_context = Context(context)
    email_subject = subject_template.render(email_context)
    email_body = body_template.render(email_context)
    email_body_full = render_to_string(
        'emails/default.html', context={'rendered_email_body': email_body})

    # Send the email
    text_message = strip_tags(email_body_full)
    email = EmailMultiAlternatives(
        to=recipient_list,
        from_email=from_email,
        subject=email_subject,
        body=text_message,
    )
    email.attach_alternative(email_body_full, "text/html")
    # Attachment?
    if attachment_filename:
        if attachment_data:
            email.attach(attachment_filename, attachment_data)
        else:
            email.attach_file(attachment_filename)
    elif attachment_data:
        email.attach('attachment', attachment_data)
    email.send()
Ejemplo n.º 47
0
def create_site(name,
                directory=SITE_DIR,
                templates_dir=TEMPLATES_DIR,
                static_dir=RESOURCES_DIR):

    if not directory:
        sys.stderr.write(
            "Please provide a site name, e.g. %s <site_name>\n\n" % NAME)
        sys.exit(1)

    sys.stdout.write("\tCopying site templates to %s\n" % directory)

    # Generate manage.py
    from django.template import Engine, Context
    engine = Engine()
    f = open(os.path.join(os.path.dirname(templates_dir), 'manage.txt'))
    template = engine.from_string(f.read())
    f.close()
    managepy_file_contents = template.render(Context({'site_name': name}))
    managepy_file = open(os.path.join(BASE_DIR, 'manage.py'), 'w+')
    managepy_file.write(managepy_file_contents)
    managepy_file.close()
    os.chmod(os.path.join(BASE_DIR, 'manage.py'), 0755)

    # copy template framework into site directory
    shutil.copytree("%s/" % templates_dir,
                    directory,
                    ignore=shutil.ignore_patterns('.svn'))

    site_resources = "%s/%s" % (static_dir, name)

    # make static dirs
    for static_dir in STATIC_DIRS:
        try:
            os.makedirs("%s/%s" % (site_resources, static_dir))
            sys.stdout.write("\tCreated %s in %s\n" %
                             (static_dir, site_resources))
        except:
            pass
Ejemplo n.º 48
0
    def library(cls, chart_id):
        if cls._library is None:
            loader = Loader(Engine())
            for filename in loader.get_template_sources('chartkick.json'):
                if os.path.exists(filename):
                    oprtions = Options()
                    oprtions.load(filename)
                    cls._library = oprtions
                    break
            else:
                cls._library = Options()

        return cls._library.get(chart_id, {})
Ejemplo n.º 49
0
def page_not_found(request, template_name='404.html'):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
    """
    context = {'request_path': request.path}
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None  # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>'
        )
        body = template.render(Context(context))
        content_type = 'text/html'
    return http.HttpResponseNotFound(body, content_type=content_type)
Ejemplo n.º 50
0
def render_html(message, etype, img_url, sender, template):
    """Docstring"""
    print(template)
    engine = Engine.get_default()
    s = MailTemplate.objects.get(pk=template).template.read().decode()
    template = engine.from_string(s)
    html = template.render(Context({
        'message': bleach.clean(message, tags=bleach.sanitizer.ALLOWED_TAGS + ['p'], strip=True),
        'etype': etype,
        'img_url': img_url,
        'from': sender,
    }))
    return transform(html)
Ejemplo n.º 51
0
    def render_django_template(self,
                               template_path,
                               context=None,
                               i18n_service=None):
        """
        Evaluate a django template by resource path, applying the provided context.
        """
        context = context or {}
        context['_i18n_service'] = i18n_service
        libraries = {
            'i18n': 'xblockutils.templatetags.i18n',
        }

        # For django 1.8, we have to load the libraries manually, and restore them once the template is rendered.
        _libraries = None
        if django.VERSION[0] == 1 and django.VERSION[1] == 8:
            _libraries = TemplateBase.libraries.copy()
            for library_name in libraries:
                library = TemplateBase.import_library(libraries[library_name])
                if library:
                    TemplateBase.libraries[library_name] = library
            engine = Engine()
        else:
            # Django>1.8 Engine can load the extra templatetag libraries itself
            # but we have to override the default installed libraries.
            from django.template.backends.django import get_installed_libraries
            installed_libraries = get_installed_libraries()
            installed_libraries.update(libraries)
            engine = Engine(libraries=installed_libraries)

        template_str = self.load_unicode(template_path)
        template = Template(template_str, engine=engine)
        rendered = template.render(Context(context))

        # Restore the original TemplateBase.libraries
        if _libraries is not None:
            TemplateBase.libraries = _libraries

        return rendered
Ejemplo n.º 52
0
def page_not_found(request, template_name='404.html'):
    context = {
        'request_path': request.path,
        'error': {
            'title': _('Page not found'),
            'message': _("We tried but couldn't find this page, sorry."),
        },
    }

    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None

    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {% raw %}{{ request_path }}{% endraw %} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'

    return HttpResponseNotFound(body, content_type=content_type)
Ejemplo n.º 53
0
 def _decorated(*args, **kwargs):  # pylint: disable=missing-docstring
     with override_settings(COMPREHENSIVE_THEME_DIR=theme_dir,
                            **changes['settings']):
         default_engine = Engine.get_default()
         dirs = default_engine.dirs[:]
         with edxmako.save_lookups():
             for template_dir in changes['template_paths']:
                 edxmako.paths.add_lookup('main',
                                          template_dir,
                                          prepend=True)
                 dirs.insert(0, template_dir)
             with patch.object(default_engine, 'dirs', dirs):
                 return func(*args, **kwargs)
Ejemplo n.º 54
0
def directory_index(path, fullpath):
    try:
        t = loader.select_template(
            ["static/directory_index.html", "static/directory_index",]
        )
    except TemplateDoesNotExist:
        t = Engine(libraries={"i18n": "django.templatetags.i18n"}).from_string(
            DEFAULT_DIRECTORY_INDEX_TEMPLATE
        )
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith("."):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += "/"
            files.append(f)
    c.update(
        {"directory": path + "/", "file_list": files,}
    )
    return HttpResponse(t.render(c))
Ejemplo n.º 55
0
    def test_include_cache(self):
        """
        {% include %} keeps resolved templates constant (#27974). The
        CounterNode object in the {% counter %} template tag is created once
        if caching works properly. Each iteration increases the counter instead
        of restarting it.

        This works as a regression test only if the cached loader
        isn't used, so the @setup decorator isn't used.
        """
        engine = Engine(
            loaders=[
                ('django.template.loaders.locmem.Loader', {
                    'template':
                    '{% for x in vars %}{% include "include" %}{% endfor %}',
                    'include': '{% include "next" %}',
                    'next': '{% load custom %}{% counter %}'
                }),
            ],
            libraries={'custom': 'template_tests.templatetags.custom'})
        output = engine.render_to_string('template', {'vars': range(9)})
        self.assertEqual(output, '012345678')
Ejemplo n.º 56
0
    def test_extends_include_missing_cachedloader(self):
        """
        Test the cache loader separately since it overrides load_template.
        """
        engine = Engine(
            debug=True,
            loaders=[
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.app_directories.Loader',
                ]),
            ])

        template = engine.get_template('test_extends_error.html')
        with self.assertRaises(TemplateDoesNotExist) as e:
            template.render(Context())
        self.assertEqual(e.exception.args[0], 'missing.html')

        # Repeat to ensure it still works when loading from the cache
        template = engine.get_template('test_extends_error.html')
        with self.assertRaises(TemplateDoesNotExist) as e:
            template.render(Context())
        self.assertEqual(e.exception.args[0], 'missing.html')
Ejemplo n.º 57
0
def _render_action_email(action, attendee, outreach_email, template):
    if isinstance(template, str):
        template = Engine.get_default().get_template(template)

    ctx = {
        "action": action,
        "contact": attendee.contact,
        "base_url": base_url(),
        "outreach_email": outreach_email,
    }
    msg_body = template.render(Context(ctx))

    return msg_body
Ejemplo n.º 58
0
def get_plugin_index_data(base_plugin, request):
    text_bits = []

    instance, plugin_type = base_plugin.get_plugin_instance()

    if instance is None or instance.plugin_type in EXCLUDED_PLUGINS:
        # this is an empty plugin or excluded from search
        return text_bits

    search_fields = getattr(instance, 'search_fields', [])
    if hasattr(instance, 'search_fulltext'):
        # check if the plugin instance has search enabled
        search_contents = instance.search_fulltext
    elif hasattr(base_plugin, 'search_fulltext'):
        # now check in the base plugin instance (CMSPlugin)
        search_contents = base_plugin.search_fulltext
    elif hasattr(plugin_type, 'search_fulltext'):
        # last check in the plugin class (CMSPluginBase)
        search_contents = plugin_type.search_fulltext
    else:
        # disabled if there's search fields defined,
        # otherwise it's enabled.
        search_contents = not bool(search_fields)

    if search_contents:
        context = RequestContext(request)
        updates = {}
        engine = Engine.get_default()

        for processor in engine.template_context_processors:
            updates.update(processor(context.request))
        context.dicts[context._processors_index] = updates

        try:
            # django-cms>=3.5
            renderer = request.toolbar.content_renderer
        except AttributeError:
            # django-cms>=3.4
            renderer = context.get('cms_content_renderer')

        plugin_contents = _render_plugin(instance, context, renderer)

        if plugin_contents:
            text_bits = get_cleaned_bits(plugin_contents)
    else:
        values = (get_field_value(instance, field) for field in search_fields)

        for value in values:
            cleaned_bits = get_cleaned_bits(value or '')
            text_bits.extend(cleaned_bits)
    return text_bits
Ejemplo n.º 59
0
    def test_extend_cached(self):
        engine = Engine(
            dirs=[
                os.path.join(RECURSIVE, "fs"),
                os.path.join(RECURSIVE, "fs2"),
                os.path.join(RECURSIVE, "fs3"),
            ],
            loaders=[
                (
                    "django.template.loaders.cached.Loader",
                    [
                        "django.template.loaders.filesystem.Loader",
                    ],
                ),
            ],
        )
        template = engine.get_template("recursive.html")
        output = template.render(Context({}))
        self.assertEqual(output.strip(),
                         "fs3/recursive fs2/recursive fs/recursive")

        cache = engine.template_loaders[0].get_template_cache
        self.assertEqual(len(cache), 3)
        expected_path = os.path.join("fs", "recursive.html")
        self.assertTrue(
            cache["recursive.html"].origin.name.endswith(expected_path))

        # Render another path that uses the same templates from the cache
        template = engine.get_template("other-recursive.html")
        output = template.render(Context({}))
        self.assertEqual(output.strip(),
                         "fs3/recursive fs2/recursive fs/recursive")

        # Template objects should not be duplicated.
        self.assertEqual(len(cache), 4)
        expected_path = os.path.join("fs", "other-recursive.html")
        self.assertTrue(
            cache["other-recursive.html"].origin.name.endswith(expected_path))
Ejemplo n.º 60
0
def page_not_found(request, exception, template_name='404.html'):
	exception_repr = ''
	try:
		message = exception.args[0]
	except (AttributeError, IndexError):
		pass
	else:
		if isinstance(message, six.text_type):
			exception_repr = t_(message, request)
	settings.request_thread_safe = threading.local()
	settings.request_thread_safe.request = request
	try :
		request.ua.status_code = 404
		request.ua.save()
	except Exception :
		pass
	if request.META.get('HTTP_AJAX') == 'true' :
		content_dict = {
			'status': 'error', 
			'content': exception_repr or t_('找不到页面', request), 
		}
		return http.HttpResponse(json.dumps(content_dict), 
								content_type="application/json")
	context = {
		'request_path': request.path,
		'exception': exception_repr,
		'request': request, 
	}
	try:
		template = loader.get_template(template_name)
		body = template.render(context, request)
		content_type = None
	except TemplateDoesNotExist:
		template = Engine().from_string('<h1>Not Found</h1><p>The requested URL'
						' {{ request_path }} was not found on this server.</p>')
		body = template.render(Context(context))
		content_type = 'text/html'
	return http.HttpResponseNotFound(body, content_type=content_type)