我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.template.TemplateDoesNotExist()。
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)
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)
def load_template(self, template_name, template_dirs=None): warnings.warn( 'The load_template() method is deprecated. Use get_template() ' 'instead.', RemovedInDjango20Warning, ) source, display_name = self.load_template_source( template_name, template_dirs, ) origin = Origin( name=display_name, template_name=template_name, loader=self, ) try: template = Template(source, 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 of the actual template that does not exist. return source, display_name else: return template, None
def bad_request(request, exception, 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') # 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 %}.
def permission_denied(request, exception, 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 7231) 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, context={'exception': force_text(exception)}) )
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))
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
def get_template_source(name, dirs=None): """Retrieves the template's source contents. :param name: Template's filename, as passed to the template loader. :param dirs: list of directories to optionally override the defaults. :return: tuple including file contents and file path. """ loaders = [] for loader in Engine.get_default().template_loaders: # The cached loader includes the actual loaders underneath if hasattr(loader, 'loaders'): loaders.extend(loader.loaders) else: loaders.append(loader) for loader in loaders: try: return loader.load_template_source(name, template_dirs=dirs) except TemplateDoesNotExist: pass raise TemplateDoesNotExist(name)
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 {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return HttpResponseNotFound(body, content_type=content_type)
def server_error(request, template_name='500.html'): if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json': return JsonResponse({ 'sentry': sentry_id_from_request(request), 'error': { 'title': _('Something went wrong'), } }, status=500) try: template = loader.get_template(template_name) except TemplateDoesNotExist: return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') message = _('Something went wrong on our side... \n Please hold on while we fix it.').replace('\n', '<br>') return HttpResponseServerError(template.render({ 'sentry': sentry_id_from_request(request), 'error': { 'title': _('Something went wrong'), 'message': message, 'sentry': _('Fault code: #'), } }))
def add_message(self, request, level, message_template, message_context=None, extra_tags=''): """ Wrapper of `django.contrib.messages.add_message`, that reads the message text from a template. """ if 'django.contrib.messages' in settings.INSTALLED_APPS: try: if message_context is None: message_context = {} message = render_to_string(message_template, message_context).strip() if message: messages.add_message(request, level, message, extra_tags=extra_tags) except TemplateDoesNotExist: pass
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 %}.
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)}) )
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))
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 %}.
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)}) )
def get_nodelist(self, node, original, context): if isinstance(node, ExtendsNode): try: if context is None: context = Context() context.template = original return handle_extendsnode(node, context) except template.TemplateSyntaxError as e: raise TemplateSyntaxError(str(e)) except template.TemplateDoesNotExist as e: raise TemplateDoesNotExist(str(e)) # Check if node is an ```if``` switch with true and false branches nodelist = [] if isinstance(node, Node): for attr in node.child_nodelists: nodelist += getattr(node, attr, []) else: nodelist = getattr(node, 'nodelist', []) return nodelist
def load_template_source(self, template_name, template_dirs=None): """ Returns a tuple containing the source and origin for the given template name. Dispatch this to the underlying loaders. """ warnings.warn( 'The load_template_sources() method is deprecated. Use ' 'get_template() or get_contents() instead.', RemovedInDjango20Warning, ) site = Site.objects.get_current() label = settings.SITELABELS.label_from_site(site) # put the prefixed template in front of the possible templates names = [os.path.join(label, template_name), template_name] for name in names: # always try to load the label-specific version first, independent from the loader for loader in self.loaders: try: return loader.load_template_source(name, template_dirs=template_dirs) except TemplateDoesNotExist: pass raise TemplateDoesNotExist("Tried %s" % ', '.join(names))
def server_error(request, template_name='500.html'): if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json': return JsonResponse({ 'sentry': sentry_id_from_request(request), 'error': { 'title': _('Something went wrong'), } }, status=500) try: template = loader.get_template(template_name) except TemplateDoesNotExist: return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return HttpResponseServerError(template.render({ 'sentry': sentry_id_from_request(request), 'error': { 'title': _('Something went wrong'), 'message': ('%s' % _('Something went wrong on our side... \n Please hold on while we fix it.')).replace('\n', '<br>'), 'sentry': _('Fault code: #'), } }))
def load_template(self, template_name, template_dirs=None): key = self.cache_key(template_name, template_dirs) template_tuple = self.template_cache.get(key) if template_tuple is TemplateDoesNotExist: raise TemplateDoesNotExist('Template not found: %s' % template_name) elif template_tuple is None: template, origin = self.find_template(template_name, template_dirs) if not hasattr(template, 'render'): try: template = template_from_string(template) 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]
def find_template(self, template_type, action_type): """look for template""" potential_templates = [] if action_type: action_type = slugify(action_type.name) potential_templates += [ u"documents/_{0}_{1}.html".format(action_type, template_type), ] potential_templates += [ "documents/_{0}.html".format(template_type), ] for template_name in potential_templates: try: get_template(template_name) return template_name except TemplateDoesNotExist: pass return None
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)
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 %}.
def load_template_source(self, template_name, template_dirs=None): """Load templates from powerpages.Page model instances. Works only with templates named: page/<page_pk>""" try: namespace, page_pk = template_name.split('/') except ValueError: pass else: if namespace == 'page': cachekey = cachekeys.template_source(page_pk) display_name = "page:%s" % page_pk source = cache.get(cachekey) if source is None: try: page = Page.objects.get(pk=page_pk) except Page.DoesNotExist: pass else: page_processor = page.get_page_processor() source = page_processor.get_template_source() cache.set(cachekey, source) display_name = "page:%s" % page_pk return source, display_name else: return source, display_name raise TemplateDoesNotExist(template_name)
def get_template(self, template_name, dirs=_dirs_undefined): try: return Template(self.engine.get_template(template_name, dirs), self) except TemplateDoesNotExist as exc: reraise(exc, self)