def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): template = "admin/cms/page/plugin/change_form.html" # django-cms 3.0 try: find_template(template) except TemplateDoesNotExist: # django-cms < 3.0 template = "admin/cms/page/plugin_change_form.html" context.update({ 'spam_protection_method': obj.spam_protection_method if obj else 0, 'recaptcha_settings': hasattr(settings, "RECAPTCHA_PUBLIC_KEY"), 'akismet_settings': hasattr(settings, "AKISMET_API_KEY"), 'parent_template': template }) return super(ContactPlugin, self).render_change_form(request, context, add, change, form_url, obj)
def init_theme_loaders(**kwargs): import loaders find_template("xadrpy/themes/base.html") #Hack: init template loaders for loader_name in conf.THEME_LOADERS: theme_loader_cls = get_class(loader_name, loaders.ThemeLoader) theme_loader = theme_loader_cls() theme_loader.load()
def _detect_template(cls, name): """ Look for template in app/model-specific location. Return path to template or None if not found. Search using app/model names for parent classes to allow inheritance. """ _class = cls # traverse parent classes up to (but not including) Lump while(Lump not in _class.__bases__): # choose the correct path for multiple inheritance base = [ base for base in _class.__bases__ if issubclass(base, Lump)][0] # (this will only take the left-most relevant path in any rare # cases involving diamond-relationships with Lump) path = '%(app_label)s/lumps/%(model_name)s/%(name)s' % { 'app_label': base._meta.app_label, 'model_name': base._meta.module_name, 'name': name, } try: #import pdb; pdb.set_trace() find_template(path) except TemplateDoesNotExist: pass else: return path _class = base return None
def find_template(template): for extension in SIMPLE_TEMPLATES_EXTENSIONS: try: loader.find_template(u"{0}.{1}".format(template, extension)) return template except: return None
def gen_all_templates(): """ Generator. Finds paths for all the templates accessible through the loaders in TEMPLATE_LOADERS. Yields tuples: (rel_path, abs_path) """ from django.template.loaders.cached import Loader as CachedLoader if not loader.template_source_loaders: # force the template loaders to populate try: loader.find_template('foo') except loader.TemplateDoesNotExist: pass loaders = [] for l in loader.template_source_loaders: if isinstance(l, CachedLoader): # flatten cached loaders, otherwise they're kinda complex loaders.extend(l.loaders) else: loaders.append(l) for l in loaders: for tupl in gen_loader_templates(l): yield tupl
def create_default_templates(sender, app, **kwargs): if app != 'post_office': return # populate django.template.loader.template_source_loaders try: find_template('hello') except Exception: pass from django.template.loader import template_source_loaders for template_name in DEFAULT_TEMPLATE_NAMES: # Pass overriding in order to project app has already created # its own email template if template_name in EMAIL_TEMPLATES_SHOULD_BE_OVERRIDED: continue if post_office_models.EmailTemplate.objects.filter( name=template_name).exists(): continue data = {'html_content': '', 'content': '', 'subject': ''} for loader in template_source_loaders: for key in data: try: data[key] = loader.load_template_source( '%s_%s_default.txt' % (template_name, key) )[0] except Exception: pass for key in data: if not data[key] and key != 'html_content': # allow html content to be blank template_full_name = '%s_%s_default.txt' % (template_name, key) raise ValueError("Cant load template %s" % (template_full_name)) post_office_models.EmailTemplate.objects.create(name=template_name, **data)
def has_template(self, name, location=[]): try: find_template(name, location) except TemplateDoesNotExist: return False else: return True
def _validate_template(self, template): if template: try: loader.find_template(template) except TemplateDoesNotExist: raise forms.ValidationError('Template does not exist.') return True
def clean_fields(self, exclude): message_dict = {} if "template_name" not in exclude and self.template_name: try: find_template(self.template_name) except TemplateDoesNotExist, err: message_dict["template_name"] = [_("Template doesn't exist.")]
def template_exists(templ): if templ is None: return False try: #loader.get_template(templ) loader.find_template(templ) except TemplateDoesNotExist: return False return True
def clean_fields(self, exclude): message_dict = {} if "template" not in exclude: try: find_template(self.template) except TemplateDoesNotExist, err: message_dict["template"] = [_("Template doesn't exist.")]
def test_templatedir_caching(self): "Check that the template directories form part of the template cache key. Refs #13573" # Retrive a template specifying a template directory to check t1, name = loader.find_template('test.html', (os.path.join(os.path.dirname(__file__), 'templates', 'first'),)) # Now retrieve the same template name, but from a different directory t2, name = loader.find_template('test.html', (os.path.join(os.path.dirname(__file__), 'templates', 'second'),)) # The two templates should not have the same content self.assertNotEqual(t1.render(Context({})), t2.render(Context({})))
def backwards_compatibility_check(template_name): backwards = False try: find_template('actstream/action.html') except TemplateDoesNotExist: backwards = True if backwards: template_name = template_name.replace('actstream/', 'activity/') return template_name
def template_exists(templ): if templ is None: return False try: # loader.get_template(templ) loader.find_template(templ) except TemplateDoesNotExist: return False return True
def test_overriden_public_template(self, open_patched): overriden_template = os.path.join(settings.MEDIA_ROOT, 'templates', 'trekking', 'trek_public.odt') def fake_exists(f, *args): if f == overriden_template: return mock.MagicMock(spec=file) raise IOError open_patched.side_effect = fake_exists find_template('trekking/trek_public.odt') open_patched.assert_called_with(overriden_template, 'rb')
def _detect_template(path): """ Look for template in given path. Return path to template or None if not found. """ try: find_template(path) return path except TemplateDoesNotExist: return None
def _get_used_template_name(template_name_list): """ Find which template of the template_names is selected by the Django loader. """ for template_name in template_name_list: try: find_template(template_name) return template_name except TemplateDoesNotExist: continue
def configure(self, options, config): """Make sure the Django template loader cache is populated.""" base.Plugin.configure(self, options, config) from django.template import loader try: loader.find_template('') except loader.TemplateDoesNotExist: pass self.sources = set() self.loader = unittest.TestLoader()
def _get_template(self, backend, part, filetype='txt'): template = "alerts/%s/%s/%s.%s" % (self.id, backend.id, part, filetype) try: find_template(template) return template except TemplateDoesNotExist: pass template = "alerts/%s/%s.%s" % (self.id, part, filetype) find_template(template) return template
def init(self, **kwargs): self.stdout.write("Collecting themes...\n") import loaders, time try: find_template("xadrpy/themes/base.html") #Hack: init template loaders for loader_name in conf.THEME_LOADERS: theme_loader_cls = get_class(loader_name, loaders.ThemeLoader) theme_loader = theme_loader_cls() theme_loader.load() except Exception, e: logger.exception("Theme loading failed: %s", e) return
def test_definition(self): template_name = 'e1/empresa_detail.html' empresa = Empresa.objects.create() result = reverse('empresa_detail', kwargs={'pk': empresa.pk}) view, args, kwargs = resolve(result) self.assertEqual(kwargs, {'pk': str(empresa.pk)}) self.assertEqual(view.func_name, 'DetailView') self.assertEqual(view.func_closure[1].cell_contents['model'], Empresa) loader.find_template(template_name)
def template(name): try: if loader.template_source_loaders is None: loader.find_template(name) for l in loader.template_source_loaders: for filepath in l.get_template_sources(name): if os.access(filepath, os.R_OK): return filepath except TemplateDoesNotExist: path = os.path.join(project_path(), project_name(), "templates", "requirejs.html") with open(path, "w") as fh: fh.write("") return path
def handle_noargs(self, **options): # Force django to calculate template_source_loaders try: find_template('notexists') except TemplateDoesNotExist: pass from django.template.loader import template_source_loaders loaders = [] for loader in template_source_loaders: if isinstance(loader, CachedLoader): loaders.extend(loader.loaders) else: loaders.append(loader) paths = set() for loader in loaders: paths.update(list(loader.get_template_sources(''))) templates = list() for path in paths: for root, dirs, files in os.walk(path): for name in files: if not name.startswith(('.', '_')) and name.endswith('.xml'): templates.append(dict({ 'root': path, 'file': os.path.join(root[len(path)+1:], name) })) storage = FileSystemStorage(settings.FEST_TEMPLATES_ROOT) print "Compile templates:" for template in templates: template_file = os.path.join(template['root'], template['file']) filename = template['file'] content = open(template_file) try: tpl = Template(content.read().decode(settings.FILE_CHARSET), template_file=template_file, template_name=filename) tpl.compile() compiled = ContentFile(tpl.template_string) finally: content.close() filename = '%s.js' % filename[:-4] print "%s -> %s" % (template['file'], filename) storage.delete(filename) storage.save(filename, compiled)
def patched_find_template(name, dirs=None): request = getattr(settings, 'request_handler', None) if request: for prefix in request.theme.template_dir_list: try: return find_template(join(prefix, name), dirs) except TemplateDoesNotExist: pass try: return find_template(name, dirs) except TemplateDoesNotExist: raise TemplateDoesNotExist(name) else: return find_template(name, dirs)
def get_old_template(self): opts = self.model._meta app_label = opts.app_label search_templates = [ "admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()), "admin/%s/change_form.html" % app_label, "admin/change_form.html" ] for template in search_templates: try: find_template(template) return template except TemplateDoesNotExist: pass
def _select_index_template(self, app_label): templates = [ 'admin/%s/index.html' % app_label, 'admin/%s_index.html' % app_label, 'admin/app_admin_index.html', ] for template_name in templates: try: find_template(template_name) return template_name except TemplateDoesNotExist: continue return 'admin/app_admin/app_index.html'
def test_regex_character_length(self): for filename in ('xab.html', 'xaa.html'): t1, name = loader.find_template(filename) self.assertNotIn(filename, loader.template_source_loaders[0].template_cache) self.assertIsNone(name) self.assertTrue(isinstance(t1, Template)) filename = 'xaaa.html' t1, name = loader.find_template(filename) self.assertIn(filename, loader.template_source_loaders[0].template_cache) self.assertIsNone(name) self.assertTrue(isinstance(t1, Template))
def test_regex_or(self): for filename in ('ya.html', 'yb.html'): t1, name = loader.find_template(filename) self.assertNotIn(filename, loader.template_source_loaders[0].template_cache) self.assertIsNone(name) self.assertTrue(isinstance(t1, Template)) filename = 'yc.html' t1, name = loader.find_template(filename) self.assertIn(filename, loader.template_source_loaders[0].template_cache) self.assertIsNone(name) self.assertTrue(isinstance(t1, Template))
def _select_bucket_template(self, app_label): templates = [ 'admin/%s/bucket.html' % app_label, 'admin/%s_bucket.html' % app_label, 'admin/app_bucket.html', ] for template_name in templates: try: find_template(template_name) return template_name except TemplateDoesNotExist: continue return 'admin/app_admin/app_bucket.html'
def handle(self, *args, **kwargs): template_name, combination = args template, origin = find_template(template_name) bits = TAG_RE.split(template) output = [] current_exp = None current_section = None for item in bits: if TAG_RE.match(item): tag, var = TOKEN_RE.match(item).groups() if tag == 'gwo_experiment': continue elif tag == 'set_experiment': current_exp = var self._fill_variations(current_exp, combination) elif tag == 'gwo_start_section': current_section = var.strip('"') elif tag == 'gwo_end_section': output.append( self.variations[current_exp][current_section]) current_section = None else: raise CommandError("Found unrecognized tag: %s" % tag) elif current_section is not None: continue else: output.append(item) print "".join(output)
def tabs_plugin_processor(instance, placeholder, rendered_content, original_context): request = original_context['request'] if isinstance(instance, TabHeaderPlugin): wrap_info = { 'wrapper_plugin': instance, 'context': original_context, 'plugins': [], 'plugin_counter': instance.tab_count, } request.wrap_info = wrap_info else: wrap_info = getattr(request, 'wrap_info', None) todo = wrap_info and wrap_info['plugin_counter'] if todo and not (instance._render_meta.text_enabled and instance.parent): wrap_info['plugin_counter'] -= 1 wrap_info['plugins'].append(rendered_content) if wrap_info['plugin_counter'] == 0 or original_context['plugin'][ 'last']: wrapper_plugin = wrap_info['wrapper_plugin'] template = find_template(wrapper_plugin.template)[0] context = wrap_info['context'] context['plugins'] = wrap_info['plugins'] request.wrap_info = None return template.render(context) else: # we're not in a wrapper, just return what we got untouched return rendered_content return u""
def test_excluding_by_regex_file_extension(self): filename = 'test.json' t1, name = loader.find_template(filename) self.assertNotIn(filename, loader.template_source_loaders[0].template_cache) self.assertIsNone(name) self.assertTrue(isinstance(t1, Template))
def test_regex_start_of_path(self): filename = 'other.txt' t1, name = loader.find_template(filename) self.assertNotIn(filename, loader.template_source_loaders[0].template_cache) self.assertIsNone(name) self.assertTrue(isinstance(t1, Template))
def test_most_things_should_cache(self): filename = 'test.html' t1, name = loader.find_template(filename) self.assertIn(filename, loader.template_source_loaders[0].template_cache) self.assertIsNone(name) self.assertTrue(isinstance(t1, Template))
def tabs_plugin_processor(instance, placeholder, rendered_content, original_context): request = original_context['request'] if isinstance(instance, TabHeaderPlugin): wrap_info = { 'wrapper_plugin': instance, 'context': original_context, 'plugins': [], 'plugin_counter': instance.tab_count, } request.wrap_info = wrap_info else: wrap_info = getattr(request, 'wrap_info', None) todo = wrap_info and wrap_info['plugin_counter'] if todo and not(instance._render_meta.text_enabled and instance.parent): wrap_info['plugin_counter'] -= 1 wrap_info['plugins'].append(rendered_content) if wrap_info['plugin_counter'] == 0 or original_context['plugin']['last']: wrapper_plugin = wrap_info['wrapper_plugin'] template = find_template(wrapper_plugin.template)[0] context = wrap_info['context'] context['plugins'] = wrap_info['plugins'] request.wrap_info = None return template.render(context) else: # we're not in a wrapper, just return what we got untouched return rendered_content return u""
def _read_agreement_file(slug, context=None): import markdown if not context: context = { 'organization': get_current_provider()} source, _ = loader.find_template('saas/agreements/legal_%s.md' % slug) return markdown.markdown(source.render(Context(context)))
def test_definition(self): template_name = 'e1/contacto_form.html' empresa = Empresa.objects.create() result = reverse('contacto_create', kwargs={'pk': empresa.pk}) view, args, kwargs = resolve(result) self.assertIs(view.func_closure[0].cell_contents.model, Empresa) self.assertTrue( isinstance(view.func_closure[0].cell_contents(), FormView)) self.assertEqual(view.func_name, 'ContactoCreateView') loader.find_template(template_name) response = self.client.post(result, CONTACTO_CREATE_FORM_VALID_DATA) self.assertRedirects(response, expected_url=reverse('empresa_detail', kwargs={'pk': empresa.pk}))
def test_regex_start_of_path_specific_dirs(self): filename = 'other.txt' look_in = os.path.join(os.path.dirname(upath(__file__)), 'templates') t1, name = loader.find_template(filename, (look_in, )) self.assertNotIn(filename, loader.template_source_loaders[0].template_cache) self.assertIsNone(name) self.assertTrue(isinstance(t1, Template))
def find_template(template_list): for template in template_list: try: #source, origin = loader.find_template_source(template) source, origin = loader.find_template(template) # Django 1.3 return (source, origin, template) except loader.TemplateDoesNotExist: pass raise loader.TemplateDoesNotExist, ', '.join(template_list)
def get_template(template_name): """ Returns a compiled Template object for the given template name, handling template inheritance recursively. Copy from django.template.loader modified to return "origin." """ template, origin = find_template(template_name) if not hasattr(template, 'render'): # template needs to be compiled template = get_template_from_string(template, origin, template_name) return template, origin
def test_definition(self): template_name = 'e1/empresa_create.html' result = reverse('empresa_create') view, args, kwargs = resolve(result) self.assertEqual(view.func_name, 'CreateView') self.assertEqual(view.func_closure[1].cell_contents['model'], Empresa) self.assertEqual( view.func_closure[1].cell_contents['form_class'].__name__, EmpresaCreateForm.__name__) loader.find_template(template_name) response = self.client.post(result, EMPRESA_CREATE_VALID_DATA) self.assertRedirects(response, expected_url=reverse('empresa_list')) response = self.client.get(result) self.assertTemplateUsed(response, template_name)
def test_definition(self): template_name = 'e1/empresa_form.html' empresa = Empresa.objects.create() result = reverse('empresa_update', kwargs={'pk': empresa.pk}) Location.objects.create() view, args, kwargs = resolve(result) self.assertEqual(kwargs, {'pk': '%s' % empresa.pk}) self.assertEqual(view.func_name, 'UpdateView') self.assertEqual(view.func_closure[1].cell_contents['model'], Empresa) self.assertEqual( view.func_closure[1].cell_contents['form_class'].__name__, EmpresaUpdateForm.__name__) loader.find_template(template_name) response = self.client.post(result, EMPRESA_UPDATE_VALID_DATA) self.assertRedirects(response, expected_url=reverse('empresa_list'))
def GetListContent(obj, context, template_path=None): template_paths = GetTemplatesPath(obj.content_type.app_label, obj.content_type.model, 'object_list', template_path) simple_obj_template_path = GetTemplatesPath(obj.content_type.app_label, obj.content_type.model, 'object', template_path)[0] try: t = find_template(simple_obj_template_path) template_paths.append("flatblocks/object_list_by_object.html") context["object_file_to_include"] = simple_obj_template_path except Exception, e: pass
def select_template_name(template_name_list): """ Given a list of template names, find the first one that exists. """ if not isinstance(template_name_list, tuple): template_name_list = tuple(template_name_list) try: return _cached_name_lookups[template_name_list] except KeyError: # Find which template of the template_names is selected by the Django loader. for template_name in template_name_list: try: find_template(template_name) except TemplateDoesNotExist: continue else: template_name = unicode(template_name) # consistent value for lazy() function. _cached_name_lookups[template_name_list] = template_name return template_name return None
def get_template_names(self, name): opts = self.model._meta app_label = opts.app_label search_templates = self._get_templates(name) + [ "%s/%ss/%s.html" % (app_label, opts.object_name.lower(), name), "%s/%s.html" % (app_label, name), "%s.html" % name ] try: from django.template.loader import find_template for template in search_templates: try: find_template(template) return [template] except TemplateDoesNotExist: pass else: raise Exception("Template does not exist!") except: # Django 1.8 support from django.template import Engine return Engine.get_default().select_template(search_templates)