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")
python类STATIC_URL的实例源码
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 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 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 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 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 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 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 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 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")