Python django.conf.settings.STATIC_URL Examples

The following are 30 code examples for showing how to use django.conf.settings.STATIC_URL(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: donation-tracker   Author: GamesDoneQuick   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def index(request, **kwargs):
    bundle = webpack_manifest.load(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__), '../ui-tracker.manifest.json')
        ),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None,
    )

    return render(
        request,
        'ui/index.html',
        {
            'event': Event.objects.latest(),
            'events': Event.objects.all(),
            'bundle': bundle.tracker,
            'CONSTANTS': mark_safe(json.dumps(constants())),
            'ROOT_PATH': reverse('tracker:ui:index'),
            'app': 'TrackerApp',
            'form_errors': {},
            'props': '{}',
        },
    ) 
Example 2
Project: coursys   Author: sfu-fas   File: context.py    License: GNU General Public License v3.0 6 votes vote down vote up
def media(request):
    """
    Add context things that we need
    """
    # A/B testing: half of instructors and TAs see a different search box
    instr_ta = is_instr_ta(request.user.username)
    instr_ta_ab = instr_ta and request.user.is_authenticated and request.user.id % 2 == 0
    # GRAD_DATE(TIME?)_FORMAT for the grad/ra/ta apps
    return {'GRAD_DATE_FORMAT': settings.GRAD_DATE_FORMAT,
            'GRAD_DATETIME_FORMAT': settings.GRAD_DATETIME_FORMAT,
            'LOGOUT_URL': settings.LOGOUT_URL,
            'LOGIN_URL': settings.LOGIN_URL,
            'STATIC_URL': settings.STATIC_URL,
            'is_instr_ta': instr_ta,
            'instr_ta_ab': instr_ta_ab,
            'request_path': request.path,
            'CourSys': product_name(request),
            'help_email': help_email(request),
            } 
Example 3
Project: GTDWeb   Author: lanbing510   File: static.py    License: GNU General Public License v2.0 6 votes vote down vote up
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") 
Example 4
Project: GTDWeb   Author: lanbing510   File: static.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 5
Project: DCRM   Author: 82Flex   File: fluent_comments_tags.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example 6
Project: bioforum   Author: reBiocoder   File: static.py    License: MIT License 6 votes vote down vote up
def do_static(parser, token):
    """
    Join 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) 
Example 7
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 6 votes vote down vote up
def check_settings(base_url=None):
    """
    Check 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") 
Example 8
Project: BikeMaps   Author: SPARLab   File: emoji.py    License: MIT License 6 votes vote down vote up
def run(self, lines):
        new_lines = []

        def emojify(match):
            emoji = match.group(1)

            if not emoji in emojis_set:
                return match.group(0)

            image = emoji + u'.png'
            url = os.path.join(settings.STATIC_URL, u'spirit', u'emojis', image).replace(u'\\', u'/')

            return u'![%(emoji)s](%(url)s)' % {'emoji': emoji, 'url': url}

        for line in lines:
            if line.strip():
                line = re.sub(ur':(?P<emoji>[a-z0-9\+\-_]+):', emojify, line, flags=re.UNICODE)

            new_lines.append(line)

        return new_lines 
Example 9
Project: substra-backend   Author: SubstraFoundation   File: sql_printing_middleware.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, request):
        response = self.get_response(request)

        if (len(connection.queries) == 0 or
                request.path_info.startswith('/favicon.ico') or
                request.path_info.startswith(settings.STATIC_URL) or
                request.path_info.startswith(settings.MEDIA_URL)):
            return response

        indentation = 2
        print(("\n\n%s\033[1;35m[SQL Queries for]\033[1;34m %s\033[0m\n" % (" " * indentation, request.path_info)))
        total_time = 0.0
        for query in connection.queries:
            if query['sql']:
                nice_sql = query['sql'].replace('"', '').replace(',', ', ')
                sql = "\033[1;31m[%s]\033[0m %s" % (query['time'], nice_sql)
                total_time = total_time + float(query['time'])
                print(("%s%s\n" % (" " * indentation, sql)))
        replace_tuple = (" " * indentation, str(total_time), str(len(connection.queries)))
        print(("%s\033[1;32m[TOTAL TIME: %s seconds (%s queries)]\033[0m" % replace_tuple))
        return response 
Example 10
Project: conf_site   Author: pydata   File: mail.py    License: MIT License 6 votes vote down vote up
def send_email(to, kind, cc=[], **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(
            "symposion/emails/%s/subject.txt" % kind, ctx
        ).strip(),
    )

    message_html = render_to_string(
        "symposion/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, cc=cc
    )
    email.attach_alternative(message_html, "text/html")
    email.send() 
Example 11
Project: django-tenants   Author: django-tenants   File: storage.py    License: MIT License 6 votes vote down vote up
def relative_static_url(self):
        url = settings.STATIC_URL
        rewrite_on = False

        try:
            if settings.REWRITE_STATIC_URLS is True:
                rewrite_on = True
                try:
                    multitenant_relative_url = settings.MULTITENANT_RELATIVE_STATIC_ROOT
                except AttributeError:
                    # MULTITENANT_RELATIVE_STATIC_ROOT is an optional setting. Use the default of just appending
                    # the tenant schema_name to STATIC_ROOT if no configuration value is provided
                    multitenant_relative_url = "%s"

                url = "/" + "/".join(s.strip("/") for s in [url, multitenant_relative_url]) + "/"

        except AttributeError:
            # REWRITE_STATIC_URLS not set - ignore
            pass

        return rewrite_on, url 
Example 12
Project: wagtail-cookiecutter-foundation   Author: chrisdev   File: wagtail_hooks.py    License: MIT License 6 votes vote down vote up
def editor_js():
    # Add extra JS files to the admin
    js_files = [
        'js/hallo-custom.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('blockquotebuttonwithclass');
        </script>
        """
    ) 
Example 13
Project: online-judge   Author: DMOJ   File: middleware.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def __call__(self, request):
        if request.user.is_authenticated:
            profile = request.profile = request.user.profile
            logout_path = reverse('auth_logout')
            login_2fa_path = reverse('login_2fa')
            webauthn_path = reverse('webauthn_assert')
            change_password_path = reverse('password_change')
            change_password_done_path = reverse('password_change_done')
            has_2fa = profile.is_totp_enabled or profile.is_webauthn_enabled
            if (has_2fa and not request.session.get('2fa_passed', False) and
                    request.path not in (login_2fa_path, logout_path, webauthn_path) and
                    not request.path.startswith(settings.STATIC_URL)):
                return HttpResponseRedirect(login_2fa_path + '?next=' + urlquote(request.get_full_path()))
            elif (request.session.get('password_pwned', False) and
                    request.path not in (change_password_path, change_password_done_path,
                                         login_2fa_path, logout_path) and
                    not request.path.startswith(settings.STATIC_URL)):
                return HttpResponseRedirect(change_password_path + '?next=' + urlquote(request.get_full_path()))
        else:
            request.profile = None
        return self.get_response(request) 
Example 14
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: static.py    License: MIT License 6 votes vote down vote up
def do_static(parser, token):
    """
    Join 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) 
Example 15
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: MIT License 6 votes vote down vote up
def check_settings(base_url=None):
    """
    Check 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") 
Example 16
Project: python   Author: Yeah-Kun   File: static.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 17
Project: django-spa   Author: metakermit   File: middleware.py    License: MIT License 6 votes vote down vote up
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. when /my/file.png is requested, serve /static/my/file.png
                directory_indexes[url[static_prefix_length:]] = static_file
        self.files.update(directory_indexes) 
Example 18
Project: django-spa   Author: metakermit   File: middleware.py    License: MIT License 6 votes vote down vote up
def find_file(self, url):
        # In debug mode, find_file() is used to serve files directly
        # from the filesystem instead of using the list in `self.files`,
        # we append the index filename so that will be served if present.
        # TODO: handle the trailing slash for the case of e.g. /welcome/
        # (should be frontend-routed)
        if url.endswith('/'):
            url += self.index_name
            self.spa_root = super(SPAMiddleware, self).find_file(url)
            return self.spa_root
        else:
            # also serve static files on /
            # e.g. when /my/file.png is requested, serve /static/my/file.png
            if (not url.startswith(settings.STATIC_URL)):
                url = os.path.join(settings.STATIC_URL, url[1:])
            return super(SPAMiddleware, self).find_file(url) 
Example 19
Project: luscan-devel   Author: blackye   File: static.py    License: GNU General Public License v2.0 6 votes vote down vote up
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") 
Example 20
Project: raveberry   Author: raveberry   File: base.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_apk_link(cls) -> str:
        local_apk = os.path.join(settings.STATIC_ROOT, "apk/shareberry.apk")
        if os.path.isfile(local_apk):
            return os.path.join(settings.STATIC_URL, "apk/shareberry.apk")
        return "https://github.com/raveberry/shareberry/raw/master/app/release/shareberry.apk" 
Example 21
Project: donation-tracker   Author: GamesDoneQuick   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def constants():
    return {
        'PRIVACY_POLICY_URL': getattr(settings, 'PRIVACY_POLICY_URL', ''),
        'SWEEPSTAKES_URL': getattr(settings, 'SWEEPSTAKES_URL', ''),
        'API_ROOT': reverse('tracker:api_v1:root'),
        'APP_NAME': 'tracker',
        'STATIC_URL': settings.STATIC_URL,
    } 
Example 22
Project: donation-tracker   Author: GamesDoneQuick   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def admin(request):
    bundle = webpack_manifest.load(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__), '../ui-tracker.manifest.json')
        ),
        settings.STATIC_URL,
        debug=settings.DEBUG,
        timeout=60,
        read_retry=None,
    )

    return render(
        request,
        'ui/index.html',
        {
            'event': Event.objects.latest(),
            'events': Event.objects.all(),
            'bundle': bundle.admin,
            'CONSTANTS': mark_safe(json.dumps(constants())),
            'ROOT_PATH': reverse('tracker:ui:admin'),
            'app': 'AdminApp',
            'form_errors': {},
            'props': mark_safe(
                json.dumps(
                    {}, ensure_ascii=False, cls=serializers.json.DjangoJSONEncoder
                )
            ),
        },
    ) 
Example 23
Project: StormOnline   Author: stormsha   File: ueditor.py    License: Apache License 2.0 5 votes vote down vote up
def block_extrahead(self, context, nodes):
        # 自己的静态目录
        js = '<script type="text/javascript" src="%s"></script>' % (settings.STATIC_URL + "ueditor/ueditor.config.js")
        # 自己的静态目录
        js += '<script type="text/javascript" src="%s"></script>' % (settings.STATIC_URL + "ueditor/ueditor.all.min.js")
        nodes.append(js)


# 新增页面 
Example 24
Project: django-echarts   Author: kinegratii   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_django_echarts_settings():
    project_echarts_settings = {k: v for k, v in DEFAULT_SETTINGS.items()}
    project_echarts_settings.update(getattr(settings, 'DJANGO_ECHARTS', {}))
    extra_settings = {
        'STATIC_URL': settings.STATIC_URL
    }
    settings_store = SettingsStore(
        echarts_settings=project_echarts_settings,
        extra_settings=extra_settings
    )
    return settings_store 
Example 25
Project: WF-website   Author: WesternFriend   File: wagtail_hooks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def editor_js():
    js_files = [
        'js/contact_person_slug.js',
    ]
    js_includes = format_html_join('\n', '<script src="{0}{1}"></script>',
                                   ((settings.STATIC_URL, filename)
                                    for filename in js_files)
                                   )
    return js_includes 
Example 26
Project: cloudless   Author: BradNeuberg   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def url(self):
        url = self.path
        url = url.replace(settings.BASE_DIR, '').replace('/train/static/', '')
        url = settings.STATIC_URL + url
        return str(url) 
Example 27
Project: wagtailinvoices   Author: SableWalnut   File: editor.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_pdf(invoice, request):
    # Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources

    def link_callback(uri, rel):
        # use short variable names
        sUrl = settings.STATIC_URL      # Typically /static/
        sRoot = settings.STATIC_ROOT    # Typically /home/userX/project_static/
        mUrl = settings.MEDIA_URL       # Typically /static/media/
        mRoot = settings.MEDIA_ROOT     # Typically /home/userX/project_static/media/

        # convert URIs to absolute system paths
        if uri.startswith(mUrl):
            path = os.path.join(mRoot, uri.replace(mUrl, ""))
        elif uri.startswith(sUrl):
            path = os.path.join(sRoot, uri.replace(sUrl, ""))

        # make sure that file exists
        if not os.path.isfile(path):
                raise Exception(
                        'media URI must start with %s or %s' % \
                        (sUrl, mUrl))
        return path

    # Render html content through html template with context
    template = get_template(settings.PDF_TEMPLATE)
    html = template.render(Context(invoice))

    # Write PDF to file
    # file = open(os.path.join(settings.MEDIA_ROOT, 'Invoice #' + str(id) + '.pdf'), "w+b")
    file = StringIO.StringIO()
    pisaStatus = pisa.CreatePDF(html, dest=file, link_callback=link_callback)

    # Return PDF document through a Django HTTP response
    file.seek(0)
    # pdf = file.read()
    # file.close()            # Don't forget to close the file handle
    return HttpResponse(file, content_type='application/pdf') 
Example 28
Project: GTDWeb   Author: lanbing510   File: widgets.py    License: GNU General Public License v2.0 5 votes vote down vote up
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) 
Example 29
Project: GTDWeb   Author: lanbing510   File: static.py    License: GNU General Public License v2.0 5 votes vote down vote up
def handle_simple(cls, path):
        return urljoin(PrefixNode.handle_simple("STATIC_URL"), path) 
Example 30
Project: GTDWeb   Author: lanbing510   File: context_processors.py    License: GNU General Public License v2.0 5 votes vote down vote up
def static(request):
    """
    Adds static-related context variables to the context.

    """
    return {'STATIC_URL': settings.STATIC_URL}