我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.STATIC_URL。
def editor_js(): js_files = [ 'javascripts/hallo.js', ] js_includes = format_html_join('\n', '<script src="{0}{1}"></script>', ((settings.STATIC_URL, filename) for filename in js_files) ) return js_includes + format_html(""" <script> registerHalloPlugin('blockQuoteButton'); registerHalloPlugin('editHtmlButton'); </script> """)
def check_settings(base_url=None): """ Checks if the staticfiles settings have sane values. """ if base_url is None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the required STATIC_URL setting.") if settings.MEDIA_URL == base_url: raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL " "settings must have different values") if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and (settings.MEDIA_ROOT == settings.STATIC_ROOT)): raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT " "settings must have different values")
def do_static(parser, token): """ Joins the given path with the STATIC_URL setting. Usage:: {% static path [as varname] %} Examples:: {% static "myapp/css/base.css" %} {% static variable_with_path %} {% static "myapp/css/base.css" as admin_base_css %} {% static variable_with_path as varname %} """ return StaticNode.handle_token(parser, token)
def send_email(to, kind, **kwargs): current_site = Site.objects.get_current() ctx = { "current_site": current_site, "STATIC_URL": settings.STATIC_URL, } ctx.update(kwargs.get("context", {})) subject = "[%s] %s" % ( current_site.name, render_to_string("emails/%s/subject.txt" % kind, ctx).strip() ) message_html = render_to_string("emails/%s/message.html" % kind, ctx) message_plaintext = strip_tags(message_html) from_email = settings.DEFAULT_FROM_EMAIL email = EmailMultiAlternatives(subject, message_plaintext, from_email, to) email.attach_alternative(message_html, "text/html") email.send()
def is_locale_independent(path): """ Returns whether the path is locale-independent. """ if (localeurl_settings.LOCALE_INDEPENDENT_MEDIA_URL and settings.MEDIA_URL and path.startswith(settings.MEDIA_URL)): return True if (localeurl_settings.LOCALE_INDEPENDENT_STATIC_URL and getattr(settings, "STATIC_URL", None) and path.startswith(settings.STATIC_URL)): return True for regex in localeurl_settings.LOCALE_INDEPENDENT_PATHS: if regex.search(path): return True return False
def test_munge_config(self): def mock_find(path): return os.path.join('/some/path/static/', path) with mock.patch('webpack.conf.find', new=mock_find) as find: munged = get_munged_config(WEBPACK_CONFIG) expected_output = WEBPACK_CONFIG_OUTPUT.format( url=settings.STATIC_URL, root=settings.STATIC_ROOT ) self.assertEqual( munged, expected_output )
def render(self, name, value, attrs=None): if attrs is None: attrs = {} # it's called "original" because it will be replaced by a copy attrs['class'] = 'hstore-original-textarea' # get default HTML from AdminTextareaWidget html = super(BaseAdminHStoreWidget, self).render(name, value, attrs) # prepare template context template_context = Context({ 'field_name': name, 'STATIC_URL': settings.STATIC_URL, 'use_svg': django.VERSION >= (1, 9), # use svg icons if django >= 1.9 }) # get template object template = get_template('happenings/hstore_%s_widget.html' % self.admin_style) # render additional html additional_html = template.render(template_context) # append additional HTML and mark as safe html = html + additional_html html = mark_safe(html) return html
def get_editor_js_for_registration(cls): js_files = cls.get_editor_js_files() js_includes = format_html_join( '\n', '<script src="{0}{1}"></script>', ((settings.STATIC_URL, filename) for filename in js_files) ) return js_includes + format_html( """ <script> window.chooserUrls.{0}Chooser = '{1}'; </script> """, cls.model._meta.object_name, urlresolvers.reverse('{}_chooser'.format(cls.model._meta.model_name)) )
def get_context_data(self, parent_context, *tag_args, **tag_kwargs): """ The main logic for the inclusion node, analogous to ``@register.inclusion_node``. """ target_object = tag_args[0] # moved one spot due to .pop(0) new_context = { 'STATIC_URL': parent_context.get('STATIC_URL', None), 'USE_THREADEDCOMMENTS': appsettings.USE_THREADEDCOMMENTS, 'target_object': target_object, } # Be configuration independent: if new_context['STATIC_URL'] is None: try: request = parent_context['request'] except KeyError: new_context.update({'STATIC_URL': settings.STATIC_URL}) else: new_context.update(context_processors.static(request)) return new_context
def _setup(self): # Check local_host with settings.STATIC_URL if self['local_host'] is not None: if settings.STATIC_URL is None: raise ValueError("The local_host item requires a no-empty settings.STATIC_URL.") if not self['local_host'].startswith('{STATIC_URL}') and not self['local_host'].startswith( settings.STATIC_URL): raise ValueError('The local_host must start with the value of settings.STATIC_URL"') if self['lib_js_host'] == 'local_host': self['lib_js_host'] = self['local_host'] if self['map_js_host'] == 'local_host': self['map_js_host'] = self['local_host'] if settings.STATIC_URL is not None: self._host_context.update({'STATIC_URL': settings.STATIC_URL}) self._host_store = HostStore( echarts_lib_name_or_host=self['lib_js_host'], echarts_map_name_or_host=self['map_js_host'], context=self._host_context )
def tabs_block_styles(): return format_html( '<link rel="stylesheet" href="' + settings.STATIC_URL + 'wagtailblocks_tabs/css/wagtailblocks_tabs.css">' ) # @hooks.register('insert_editor_js') # def tabs_block_scripts(): # js_files = [ # 'wagtailblocks_tabs/js/tabs.js', # ] # js_includes = format_html_join( # '\n', '<script src="{0}{1}"></script>', # ((settings.STATIC_URL, filename) for filename in js_files) # ) # return js_includes + format_html( # """ # <script> # $( document ).ready(tabs_block_init()); # </script> # """ # )
def configure_from_settings(self, settings): # Default configuration self.charset = settings.FILE_CHARSET self.autorefresh = settings.DEBUG self.use_finders = settings.DEBUG self.static_prefix = urlparse(settings.STATIC_URL or '').path if settings.DEBUG: self.max_age = 0 # Allow settings to override default attributes for attr in self.config_attrs: settings_key = 'WHITENOISE_{0}'.format(attr.upper()) try: value = getattr(settings, settings_key) except AttributeError: pass else: value = decode_if_byte_string(value) setattr(self, attr, value) self.static_prefix = ensure_leading_trailing_slash(self.static_prefix) self.static_root = decode_if_byte_string(settings.STATIC_ROOT)
def globalContext(request, nav=NAV): rainbow = utils.getRainbowFromSize(len(nav)) return { 'current': resolve(request.path_info).url_name, 'static_url': (settings.STATIC_FULL_URL + settings.STATIC_URL).replace('//static', '/static'), 'site_name': 'db0.company', 'site_description': 'Deby Lepage Official Website', 'debug': settings.DEBUG, 'static_files_version': '2', 'rainbow': [( (index * (100/len(RAINBOW))), ((index + 1) * (100 / (len(RAINBOW)))), color, ) for index, color in enumerate(RAINBOW)], 'nav': [tuple(list(info) + [rainbow[index]]) for index, info in enumerate(nav)], }
def test_if_preview_content_is_none(self): # monkey patch from wiki.core.plugins import registry registry._cache = {'ham': 'spam'} article = Article.objects.create() output = wiki_render({}, article) assertCountEqual(self, self.keys, output) self.assertEqual(output['article'], article) self.assertEqual(output['content'], None) self.assertEqual(output['preview'], False) self.assertEqual(output['plugins'], {'ham': 'spam'}) self.assertEqual(output['STATIC_URL'], django_settings.STATIC_URL) self.assertEqual(output['CACHE_TIMEOUT'], settings.CACHE_TIMEOUT) # Additional check self.render({'article': article, 'pc': None})
def update_files_dictionary(self, *args): super(SPAMiddleware, self).update_files_dictionary(*args) index_page_suffix = '/' + self.index_name index_name_length = len(self.index_name) static_prefix_length = len(settings.STATIC_URL) - 1 directory_indexes = {} for url, static_file in self.files.items(): if url.endswith(index_page_suffix): # For each index file found, add a corresponding URL->content # mapping for the file's parent directory, # so that the index page is served for # the bare directory URL ending in '/'. parent_directory_url = url[:-index_name_length] directory_indexes[parent_directory_url] = static_file # remember the root page for any other unrecognised files # to be frontend-routed self.spa_root = static_file else: # also serve static files on / # e.g. serve /static/my/file.png on /my/file.png directory_indexes[url[static_prefix_length:]] = static_file self.files.update(directory_indexes)
def serversearch_js(search_id): attributes = { a.pk: { 'multi': a.multi, 'type': a.type, } for a in Attribute.objects.all() } return { 'attributes_json': json.dumps(attributes), 'filters_json': json.dumps( [ f.__name__ for f in filter_classes # TODO Don't check for "Deprecated" if f != ExactMatch and not f.__doc__.startswith('Deprecated') ] ), 'search_id': search_id, 'STATIC_URL': settings.STATIC_URL }
def enable_source(): js_files = [ 'js/tinymce-textcolor-plugin.js', ] js_includes = format_html_join( '\n', '<script src="{0}{1}"></script>', ((settings.STATIC_URL, filename) for filename in js_files) ) return js_includes + format_html( """ <script> registerHalloPlugin('hallohtml'); registerMCEPlugin('textcolor'); </script> """ )
def render(self, context): """ render the img tag with specified attributes """ name = self.name.resolve(context) attrs = [] for k, v in self.attrs.iteritems(): attrs.append('%s="%s"' % (k, v.resolve(context))) if attrs: attrs = " %s" % " ".join(attrs) else: attrs = "" return """<img src="%spinax/img/silk/icons/%s.png"%s />""" % ( settings.STATIC_URL, name, attrs, )
def get_pony_urls(): """Function to return some pony urls which will not change.""" base_url = "{url}{staticpath}images/pony[size].png".format( url=settings.SOCIALHOME_URL, staticpath=settings.STATIC_URL ) return [ base_url.replace("[size]", "300"), base_url.replace("[size]", "100"), base_url.replace("[size]", "50") ]
def editor_css(): return format_html( '<link rel="stylesheet" href="%(static_url)sdemo/css/' 'admin-streamfield-styles.css">' % {'static_url': settings.STATIC_URL} )
def editor_css(): return format_html(""" <link href="{0}{1}" rel="stylesheet" type="text/x-scss" /> """, settings.STATIC_URL, 'vendor/font-awesome/scss/font-awesome.scss')
def handle(self, *args, **options): call_subprocess('./node_modules/.bin/webpack --config webpack.config.js') for each in settings.WEB_PACK_FILES: directory = settings.BASE_DIR + '/static/webpack_bundles/' css_file = max([os.path.join(directory, d) for d in os.listdir(directory) if d.startswith(each['webpack_js']) and d.endswith('css')], key=os.path.getmtime) js_file = max([os.path.join(directory, d) for d in os.listdir(directory) if d.startswith(each['webpack_js']) and d.endswith('js')], key=os.path.getmtime) if settings.ENABLE_DJANGO_WEBPACK_S3_STORAGES: upload_to_s3(css_file) upload_to_s3(js_file) import re regex = r'(.*?<link rel="stylesheet" type="text/css" href=")(.*?)(" id="packer_css"/>.*?<script id="packer_js" src=")(.*?)(" type="text/javascript"></script>.*)' with open(each['html_file_name'], 'r+') as f: content = f.read() m = re.match(regex, content, re.DOTALL) href = settings.STATIC_URL + css_file.split('/static/')[-1] src = settings.STATIC_URL + js_file.split('/static/')[-1] content = m.group(1) + href + m.group(3) + src + m.group(5) with open(each['html_file_name'], 'w') as f: f.write(content) result = {'message': "Successfully Created Compressed CSS, JS Files"} return json.dumps(result)
def absolute_path(self, path, prefix=None): if path.startswith(('http://', 'https://', '/')): return path if prefix is None: if settings.STATIC_URL is None: # backwards compatibility prefix = settings.MEDIA_URL else: prefix = settings.STATIC_URL return urljoin(prefix, path)
def staticfiles_urlpatterns(prefix=None): """ Helper function to return a URL pattern for serving static files. """ if prefix is None: prefix = settings.STATIC_URL return static(prefix, view=serve) # Only append if urlpatterns are empty
def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = settings.STATIC_ROOT if base_url is None: base_url = settings.STATIC_URL check_settings(base_url) super(StaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) # FileSystemStorage fallbacks to MEDIA_ROOT when location # is empty, so we restore the empty value. if not location: self.base_location = None self.location = None
def render(self, name, value, attrs=None): # If a string reaches here (via a validation error on another # field) then just reconstruct the Geometry. if isinstance(value, six.string_types): value = self.deserialize(value) if value: # Check that srid of value and map match if value.srid != self.map_srid: try: ogr = value.ogr ogr.transform(self.map_srid) value = ogr except gdal.GDALException as err: logger.error( "Error transforming geometry from srid '%s' to srid '%s' (%s)" % ( value.srid, self.map_srid, err) ) context = self.build_attrs( attrs, name=name, module='geodjango_%s' % name.replace('-', '_'), # JS-safe serialized=self.serialize(value), geom_type=gdal.OGRGeomType(self.attrs['geom_type']), STATIC_URL=settings.STATIC_URL, LANGUAGE_BIDI=translation.get_language_bidi(), ) return loader.render_to_string(self.template_name, context)
def get_static_prefix(parser, token): """ Populates a template variable with the static prefix, ``settings.STATIC_URL``. Usage:: {% get_static_prefix [as varname] %} Examples:: {% get_static_prefix %} {% get_static_prefix as static_prefix %} """ return PrefixNode.handle_token(parser, token, "STATIC_URL")