我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.TEMPLATES。
def check_duplicate_template_settings(app_configs, **kwargs): if settings.TEMPLATES: values = [ 'TEMPLATE_DIRS', 'ALLOWED_INCLUDE_ROOTS', 'TEMPLATE_CONTEXT_PROCESSORS', 'TEMPLATE_DEBUG', 'TEMPLATE_LOADERS', 'TEMPLATE_STRING_IF_INVALID', ] duplicates = [ value for value in values if getattr(settings, value) != getattr(global_settings, value) ] if duplicates: return [Warning( "The standalone TEMPLATE_* settings were deprecated in Django " "1.8 and the TEMPLATES dictionary takes precedence. You must " "put the values of the following settings into your default " "TEMPLATES dict: %s." % ", ".join(duplicates), id='1_8.W001', )] return []
def __getitem__(self, alias): try: return self._engines[alias] except KeyError: try: params = self.templates[alias] except KeyError: raise InvalidTemplateEngineError( "Could not find config for '{}' " "in settings.TEMPLATES".format(alias)) # If importing or initializing the backend raises an exception, # self._engines[alias] isn't set and this code may get executed # again, so we must preserve the original params. See #24265. params = params.copy() backend = params.pop('BACKEND') engine_cls = import_string(backend) engine = engine_cls(params) self._engines[alias] = engine return engine
def check_duplicate_template_settings(app_configs, **kwargs): if settings.TEMPLATES: values = [ 'TEMPLATE_DIRS', 'TEMPLATE_CONTEXT_PROCESSORS', 'TEMPLATE_DEBUG', 'TEMPLATE_LOADERS', 'TEMPLATE_STRING_IF_INVALID', ] defined = [value for value in values if getattr(settings, value, None)] if defined: return [Warning( "The standalone TEMPLATE_* settings were deprecated in Django " "1.8 and the TEMPLATES dictionary takes precedence. You must " "put the values of the following settings into your default " "TEMPLATES dict: %s." % ", ".join(defined), id='1_8.W001', )] return []
def test_get_contents(self): """ Test the get_contents function on the master.html template. Avoid using the DjangoTemplates class due to frequent changes between versions. """ templates_dir = settings.TEMPLATES[0]['DIRS'][0] master_html = templates_dir + '/master.html' contents = get_contents(filepath=master_html) self.assertIn('DOCTYPE', contents) self.assertIn('html', contents) self.assertIn('head', contents) self.assertIn('title', contents) self.assertIn('body', contents) self.assertIn('{% block title %}', contents) self.assertIn('{% block body %}', contents)
def setUpClass(cls): """ The setUpClass is used because the templates paths are not changed in the following tests. """ super(TestBase, cls).setUpClass() # Find directories with templates templates_dir = settings.TEMPLATES[0]['DIRS'][0] app = apps.get_app_config('app') app_templates = os.path.join(app.path, 'templates', 'app', 'templates') app_tags = os.path.join(app.path, 'templates', 'app', 'tags') # Save the path of each template for further testing cls.master_template = os.path.join(templates_dir, 'master.html') cls.tag_template = os.path.join(app_tags, 'tag_template.html') cls.double_loads = os.path.join(app_templates, 'double_loads.html') cls.with_tags = os.path.join(app_templates, 'with_tags.html') cls.without_tags = os.path.join(app_templates, 'without_tags.html') cls.from_syntax_with_tags = os.path.join(app_templates, 'from_syntax_with_tags.html') cls.from_syntax_without_tags = os.path.join(app_templates, 'from_syntax_without_tags.html') cls.double_member_load = os.path.join(app_templates, 'double_member_load.html') cls.only_filter = os.path.join(app_templates, 'only_filter.html')
def test_cached_show_placeholder_sekizai(self): from django.core.cache import cache cache.clear() from cms.test_utils import project template_dir = os.path.join(os.path.dirname(project.__file__), 'templates', 'alt_plugin_templates', 'show_placeholder') page = create_page('Test', 'col_two.html', 'en') placeholder = page.placeholders.all()[0] add_plugin(placeholder, TextPlugin, 'en', body='HIDDEN') request = RequestFactory().get('/') request.user = self.get_staff_user_with_no_permissions() request.current_page = page override = {'TEMPLATES': deepcopy(settings.TEMPLATES)} override['TEMPLATES'][0]['DIRS'] = [template_dir] with self.settings(**override): template = "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'en' 1 %}{% render_block 'js' %}" output = self.render_template_obj(template, {'page': page, 'slot': placeholder.slot}, request) self.assertIn('JAVASCRIPT', output)
def check_sekizai(output): with output.section("Sekizai") as section: if is_installed('sekizai'): section.success("Sekizai is installed") else: section.error("Sekizai is not installed, could not find 'sekizai' in INSTALLED_APPS") processors = list(chain(*[template['OPTIONS'].get('context_processors', []) for template in settings.TEMPLATES])) if 'sekizai.context_processors.sekizai' in processors: section.success("Sekizai template context processor is installed") else: section.error("Sekizai template context processor is not installed, could not find 'sekizai.context_processors.sekizai' in TEMPLATES option context_processors") for template, _ in get_cms_setting('TEMPLATES'): if template == constants.TEMPLATE_INHERITANCE_MAGIC: continue if validate_template(template, ['js', 'css']): section.success("Sekizai namespaces 'js' and 'css' found in %r" % template) else: section.error("Sekizai namespaces 'js' and 'css' not found in %r" % template) if section.successful: section.finish_success("Sekizai configuration okay") else: section.finish_error("Sekizai configuration has errors")
def deprecations(output): # deprecated placeholder_tags scan (1 in 3.1) templates_dirs = getattr(settings, 'TEMPLATES', [])[0]['DIRS'] templates_dirs.extend( [os.path.join(path, 'templates') for path in get_app_paths()] ) with output.section('Usage of deprecated placeholder_tags') as section: for template_dir in templates_dirs: for tokens, path in _load_all_templates(template_dir): for token in tokens: if token.token_type == TOKEN_BLOCK: bits = token.split_contents() if bits[0] == 'load' and 'placeholder_tags' in bits: section.warn( 'Usage of deprecated template tag library ' 'placeholder tags in template %s' % path )
def check_setting_app_dirs_loaders(app_configs, **kwargs): passed_check = True for conf in settings.TEMPLATES: if not conf.get('APP_DIRS'): continue if 'loaders' in conf.get('OPTIONS', {}): passed_check = False return [] if passed_check else [E001]
def __init__(self, templates=None): """ templates is an optional list of template engine definitions (structured like settings.TEMPLATES). """ self._templates = templates self._engines = {}
def check_string_if_invalid_is_string(app_configs, **kwargs): errors = [] for conf in settings.TEMPLATES: string_if_invalid = conf.get('OPTIONS', {}).get('string_if_invalid', '') if not isinstance(string_if_invalid, six.string_types): error = copy.copy(E002) error.msg = error.msg.format(string_if_invalid, type(string_if_invalid).__name__) errors.append(error) return errors
def enable(self): return override_settings(TEMPLATES=[{ **settings.TEMPLATES[0], 'BACKEND': self.ENGINE_BACKENDS[self] }])
def test_stacktraces_have_templates(client, django_elasticapm_client): # only Django 1.9+ have the necessary information stored on Node/Template # instances when TEMPLATE_DEBUG = False TEMPLATE_DEBUG = django.VERSION < (1, 9) with mock.patch("elasticapm.traces.TransactionsStore.should_collect") as should_collect: should_collect.return_value = False TEMPLATES_copy = deepcopy(settings.TEMPLATES) TEMPLATES_copy[0]['OPTIONS']['debug'] = TEMPLATE_DEBUG with override_settings( TEMPLATE_DEBUG=TEMPLATE_DEBUG, TEMPLATES=TEMPLATES_copy, **middleware_setting(django.VERSION, [ 'elasticapm.contrib.django.middleware.TracingMiddleware' ]) ): resp = client.get(reverse("render-heavy-template")) assert resp.status_code == 200 transactions = django_elasticapm_client.instrumentation_store.get_all() assert len(transactions) == 1 transaction = transactions[0] assert transaction['result'] == 'HTTP 2xx' spans = transaction['spans'] assert len(spans) == 2, [t['name'] for t in spans] expected_names = {'list_users.html', 'something_expensive'} assert {t['name'] for t in spans} == expected_names assert spans[0]['name'] == 'something_expensive' # Find the template for frame in spans[0]['stacktrace']: if frame['lineno'] == 4 and frame['filename'].endswith( 'django/testapp/templates/list_users.html' ): break else: assert False is True, "Template was not found"
def _template_names(proj_only=False): for engine in settings.TEMPLATES: if (engine['BACKEND'] == 'django.template.backends.django.DjangoTemplates'): for template_dir in chain(engine['DIRS'], get_app_template_dirs('templates')): if not proj_only or template_dir.startswith(settings.BASE_DIR): for dirpath, dirnames, filenames in os.walk(template_dir): for template_name in filenames: yield os.path.join(dirpath[len(template_dir)+1:], template_name) else: raise NotImplementedError( "Currently only supports default DjangoTemplates backend." )