Python django.template.TemplateDoesNotExist() Examples

The following are 30 code examples for showing how to use django.template.TemplateDoesNotExist(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.template , or try the search function .

Example 1
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_html_renderer.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        super(TestMMVHTMLRenderer, self).setUp()

        """
        Monkeypatch get_template
        Taken from DRF Tests
        """
        self.get_template = django.template.loader.get_template

        def get_template(template_name, dirs=None):
            if template_name == 'test.html':
                return engines['django'].from_string("<html>test: {{ data }}</html>")
            raise TemplateDoesNotExist(template_name)

        def select_template(template_name_list, dirs=None, using=None):
            if template_name_list == ['test.html']:
                return engines['django'].from_string("<html>test: {{ data }}</html>")
            raise TemplateDoesNotExist(template_name_list[0])

        django.template.loader.get_template = get_template
        django.template.loader.select_template = select_template 
Example 2
Project: django-herald   Author: worthwhile   File: base.py    License: MIT License 6 votes vote down vote up
def render(self, render_type, context):
        """
        Renders the template

        :param render_type: the content type to render
        :param context: context data dictionary
        :return: the rendered content
        """

        assert render_type in self.render_types, 'Invalid Render Type'

        try:
            content = render_to_string('herald/{}/{}.{}'.format(
                render_type,
                self.template_name,
                'txt' if render_type == 'text' else render_type
            ), context)
        except TemplateDoesNotExist:
            content = None

            if settings.DEBUG:
                raise

        return content 
Example 3
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 4
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
def bad_request(request, template_name='400.html'):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    return http.HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example 5
Project: GTDWeb   Author: lanbing510   File: static.py    License: GNU General Public License v2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine().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)) 
Example 6
Project: telemetry-analysis-service   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    500 error handler.

    :template: :file:`500.html`
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_500_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseServerError(
            "<h1>Server Error (500)</h1>", content_type="text/html"
        )
    return http.HttpResponseServerError(template.render(request=request))


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example 7
Project: telemetry-analysis-service   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
    """
    Permission denied (403) handler.

    :template: :file:`403.html`

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_403_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseForbidden(
            "<h1>403 Forbidden</h1>", content_type="text/html"
        )
    return http.HttpResponseForbidden(
        template.render(request=request, context={"exception": force_text(exception)})
    ) 
Example 8
Project: bioforum   Author: reBiocoder   File: defaults.py    License: MIT License 6 votes vote down vote up
def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_400_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    # No exception content is passed to the template, to not disclose any sensitive information.
    return HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example 9
Project: bioforum   Author: reBiocoder   File: defaults.py    License: MIT License 6 votes vote down vote up
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_403_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return HttpResponseForbidden(
        template.render(request=request, context={'exception': str(exception)})
    ) 
Example 10
Project: bioforum   Author: reBiocoder   File: static.py    License: MIT License 6 votes vote down vote up
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)) 
Example 11
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 6 votes vote down vote up
def get_template(self, template_name, skip=None):
        """
        Call self.get_template_sources() and return a Template object for
        the first template matching template_name. If skip is provided, ignore
        template origins in skip. This is used to avoid recursion during
        template extending.
        """
        tried = []

        for origin in self.get_template_sources(template_name):
            if skip is not None and origin in skip:
                tried.append((origin, 'Skipped'))
                continue

            try:
                contents = self.get_contents(origin)
            except TemplateDoesNotExist:
                tried.append((origin, 'Source does not exist'))
                continue
            else:
                return Template(
                    contents, origin, origin.template_name, self.engine,
                )

        raise TemplateDoesNotExist(template_name, tried=tried) 
Example 12
Project: waliki   Author: mgaitan   File: waliki_tags.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def entry_point(context, block_name):
    """include an snippet at the bottom of a block, if it exists

    For example, if the plugin with slug 'attachments' is registered

       waliki/attachments_edit_content.html  will be included with

        {% entry_point 'edit_content' %}

    which is declared at the bottom of the block 'content' in edit.html
    """
    from waliki.plugins import get_plugins
    includes = []
    for plugin in get_plugins():
        template_name = 'waliki/%s_%s.html' % (plugin.slug, block_name)
        try:
            # template exists
            template.loader.get_template(template_name)
            includes.append(template_name)
        except template.TemplateDoesNotExist:
            continue
    context.update({'includes': includes})
    return context 
Example 13
Project: website   Author: outreachy   File: email.py    License: GNU General Public License v3.0 6 votes vote down vote up
def approval_status_changed(obj, request, **kwargs):
    get_recipients = {
        obj.PENDING: obj.get_approver_email_list,
        obj.WITHDRAWN: obj.get_approver_email_list,
        obj.APPROVED: obj.get_submitter_email_list,
        obj.REJECTED: obj.get_submitter_email_list,
    }[obj.approval_status]

    # produces template names like "home/email/project-pending.txt"
    template = "{}/email/{}-{}.txt".format(
            obj._meta.app_label,
            obj._meta.model_name,
            obj.get_approval_status_display().lower())

    try:
        send_template_mail(template, {
                obj._meta.model_name: obj,
            },
            request=request,
            recipient_list=get_recipients(),
            **kwargs)
    except TemplateDoesNotExist:
        logger.info(
            "not sending approval status change email because %s does not exist",
            template, exc_info=True) 
Example 14
Project: website   Author: outreachy   File: template_includes.py    License: GNU General Public License v3.0 6 votes vote down vote up
def show_includes(template_path, seen, depth=0):
    if template_path in seen:
        return
    print("  " * depth + template_path)
    seen.add(template_path)

    try:
        template = loader.get_template(template_path).template
    except TemplateDoesNotExist:
        print("  " * depth + "*** previous template not found!")
        return

    for included in re.findall(r"{%\s*include\s+([^\s]*)[^%]*%}", template.source):
        if included[0] in "\"'":
            show_includes(included[1:-1], seen, depth + 1)
        else:
            print("  " * (depth + 1) + "*** template name given by expression:", repr(included)) 
Example 15
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: defaults.py    License: MIT License 6 votes vote down vote up
def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_400_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    # No exception content is passed to the template, to not disclose any sensitive information.
    return HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example 16
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: defaults.py    License: MIT License 6 votes vote down vote up
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_403_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return HttpResponseForbidden(
        template.render(request=request, context={'exception': str(exception)})
    ) 
Example 17
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: static.py    License: MIT License 6 votes vote down vote up
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 fullpath.iterdir():
        if not f.name.startswith('.'):
            url = str(f.relative_to(fullpath))
            if f.is_dir():
                url += '/'
            files.append(url)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example 18
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: base.py    License: MIT License 6 votes vote down vote up
def get_template(self, template_name, skip=None):
        """
        Call self.get_template_sources() and return a Template object for
        the first template matching template_name. If skip is provided, ignore
        template origins in skip. This is used to avoid recursion during
        template extending.
        """
        tried = []

        for origin in self.get_template_sources(template_name):
            if skip is not None and origin in skip:
                tried.append((origin, 'Skipped'))
                continue

            try:
                contents = self.get_contents(origin)
            except TemplateDoesNotExist:
                tried.append((origin, 'Source does not exist'))
                continue
            else:
                return Template(
                    contents, origin, origin.template_name, self.engine,
                )

        raise TemplateDoesNotExist(template_name, tried=tried) 
Example 19
Project: python   Author: Yeah-Kun   File: defaults.py    License: Apache License 2.0 6 votes vote down vote up
def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_400_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    # No exception content is passed to the template, to not disclose any sensitive information.
    return http.HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example 20
Project: python   Author: Yeah-Kun   File: defaults.py    License: Apache License 2.0 6 votes vote down vote up
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_403_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(
        template.render(request=request, context={'exception': force_text(exception)})
    ) 
Example 21
Project: python   Author: Yeah-Kun   File: static.py    License: Apache License 2.0 6 votes vote down vote up
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)) 
Example 22
Project: python   Author: Yeah-Kun   File: dummy.py    License: Apache License 2.0 6 votes vote down vote up
def get_template(self, template_name):
        tried = []
        for template_file in self.iter_template_filenames(template_name):
            try:
                with io.open(template_file, encoding=settings.FILE_CHARSET) as fp:
                    template_code = fp.read()
            except IOError as e:
                if e.errno == errno.ENOENT:
                    tried.append((
                        Origin(template_file, template_name, self),
                        'Source does not exist',
                    ))
                    continue
                raise

            return Template(template_code)

        else:
            raise TemplateDoesNotExist(template_name, tried=tried, backend=self) 
Example 23
Project: python   Author: Yeah-Kun   File: cached.py    License: Apache License 2.0 6 votes vote down vote up
def load_template(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template() method is deprecated. Use get_template() '
            'instead.', RemovedInDjango20Warning,
        )
        key = self.cache_key(template_name, template_dirs)
        template_tuple = self.template_cache.get(key)
        # A cached previous failure:
        if template_tuple is TemplateDoesNotExist:
            raise TemplateDoesNotExist(template_name)
        elif template_tuple is None:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = Template(template, origin, template_name, self.engine)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning the source and display name for the template
                    # we were asked to load. This allows for correct identification (later)
                    # of the actual template that does not exist.
                    self.template_cache[key] = (template, origin)
            self.template_cache[key] = (template, None)
        return self.template_cache[key] 
Example 24
Project: python   Author: Yeah-Kun   File: eggs.py    License: Apache License 2.0 6 votes vote down vote up
def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        warnings.warn(
            'The load_template_sources() method is deprecated. Use '
            'get_template() or get_contents() instead.',
            RemovedInDjango20Warning,
        )
        for origin in self.get_template_sources(template_name):
            try:
                return self.get_contents(origin), origin.name
            except TemplateDoesNotExist:
                pass
        raise TemplateDoesNotExist(template_name) 
Example 25
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def service_unavailable(request, *args, **kwargs):
    template = settings.FEATUREFLAGS_DISABLED_TEMPLATE
    try:
        return render(request, template, status=503)
    except TemplateDoesNotExist:
        return render(request, 'featureflags/service_unavailable.html', status=503) 
Example 26
Project: trove-dashboard   Author: openstack   File: tabs.py    License: Apache License 2.0 5 votes vote down vote up
def get_template_name(self, request):
        instance = self.tab_group.kwargs['instance']
        template_file = ('project/databases/_detail_overview_%s.html' %
                         self._get_template_type(instance.datastore['type']))
        try:
            template.loader.get_template(template_file)
            return template_file
        except template.TemplateDoesNotExist:
            # This datastore type does not have a template file
            # Just use the base template file
            return ('project/databases/_detail_overview.html') 
Example 27
Project: trove-dashboard   Author: openstack   File: tabs.py    License: Apache License 2.0 5 votes vote down vote up
def get_template_name(self, request):
        cluster = self.tab_group.kwargs['cluster']
        template_file = ('project/database_clusters/_detail_overview_%s.html'
                         % self._get_template_type(cluster.datastore['type']))
        try:
            template.loader.get_template(template_file)
            return template_file
        except template.TemplateDoesNotExist:
            # This datastore type does not have a template file
            # Just use the base template file
            return ('project/database_clusters/_detail_overview.html') 
Example 28
Project: django-herald   Author: worthwhile   File: test_notifications.py    License: MIT License 5 votes vote down vote up
def test_render_invalid_template_debug(self):
        class DummyNotification(NotificationBase):
            render_types = ['text']
            template_name = 'does_not_exist'

        with self.assertRaises(TemplateDoesNotExist):
            DummyNotification().render('text', {}) 
Example 29
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 5 votes vote down vote up
def server_error(request, template_name='500.html'):
    """
    500 error handler.

    Templates: :template:`500.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
    return http.HttpResponseServerError(template.render()) 
Example 30
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 5 votes vote down vote up
def permission_denied(request, template_name='403.html'):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 2616) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(template.render(request=request))