Python django.conf.settings.MEDIA_URL Examples

The following are 30 code examples of django.conf.settings.MEDIA_URL(). 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 also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: static.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def get_media_prefix(parser, token):
    """
    Populates a template variable with the media prefix,
    ``settings.MEDIA_URL``.

    Usage::

        {% get_media_prefix [as varname] %}

    Examples::

        {% get_media_prefix %}
        {% get_media_prefix as media_prefix %}

    """
    return PrefixNode.handle_token(parser, token, "MEDIA_URL") 
Example #2
Source File: homepage_tags.py    From foundation.mozilla.org with Mozilla Public License 2.0 6 votes vote down vote up
def homepage_image_with_class(context, path, classname):
    root = settings.MEDIA_URL

    if settings.USE_S3:
        awsl = settings.AWS_LOCATION
        awscd = settings.AWS_S3_CUSTOM_DOMAIN
        if awscd in root and awsl not in root:
            old = awscd
            new = awscd + '/' + awsl
            root = root.replace(old, new)

    url = '{}{}'.format(root, path)

    return {
        'url': url,
        'classname': classname,
    } 
Example #3
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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") 
Example #4
Source File: storage.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, location=None, base_url=None, file_permissions_mode=None,
            directory_permissions_mode=None):
        if location is None:
            location = settings.MEDIA_ROOT
        self.base_location = location
        self.location = abspathu(self.base_location)
        if base_url is None:
            base_url = settings.MEDIA_URL
        elif not base_url.endswith('/'):
            base_url += '/'
        self.base_url = base_url
        self.file_permissions_mode = (
            file_permissions_mode if file_permissions_mode is not None
            else settings.FILE_UPLOAD_PERMISSIONS
        )
        self.directory_permissions_mode = (
            directory_permissions_mode if directory_permissions_mode is not None
            else settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS
        ) 
Example #5
Source File: utils.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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") 
Example #6
Source File: static.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def get_media_prefix(parser, token):
    """
    Populates a template variable with the media prefix,
    ``settings.MEDIA_URL``.

    Usage::

        {% get_media_prefix [as varname] %}

    Examples::

        {% get_media_prefix %}
        {% get_media_prefix as media_prefix %}

    """
    return PrefixNode.handle_token(parser, token, "MEDIA_URL") 
Example #7
Source File: utils.py    From python2017 with MIT License 6 votes vote down vote up
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") 
Example #8
Source File: utils.py    From Hands-On-Application-Development-with-PyCharm with 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 #9
Source File: static.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def static(prefix, view='django.views.static.serve', **kwargs):
    """
    Helper function to return a URL pattern for serving files in debug mode.

    from django.conf import settings
    from django.conf.urls.static import static

    urlpatterns = patterns('',
        # ... the rest of your URLconf goes here ...
    ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

    """
    # No-op if not in debug mode or an non-local prefix
    if not settings.DEBUG or (prefix and '://' in prefix):
        return []
    elif not prefix:
        raise ImproperlyConfigured("Empty static prefix not permitted")
    return patterns('',
        url(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs),
    ) 
Example #10
Source File: sql_printing_middleware.py    From substra-backend with 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 #11
Source File: __init__.py    From volontulo with MIT License 6 votes vote down vote up
def homepage(request):
    u"""Main view of app.

    We will display page with few step CTA links?

    :param request: WSGIRequest instance
    """
    if logged_as_admin(request):
        offers = Offer.objects.get_for_administrator()
    else:
        offers = Offer.objects.get_weightened()

    return render(
        request,
        "homepage.html",
        {
            'offers': offers,
            'MEDIA_URL': settings.MEDIA_URL,
        }
    ) 
Example #12
Source File: utils.py    From bioforum with 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 #13
Source File: adminlte_options.py    From django-adminlte-ui with MIT License 6 votes vote down vote up
def get_adminlte_option(option_name, request=None):
    config_ = {}
    config_list = Options.objects.filter(valid=True)

    if config_list.filter(option_name=option_name):
        config_[option_name] = config_list.get(
            option_name=option_name).option_value
        if request and option_name == 'avatar_field':
            try:
                # request.user.head_avatar
                image_path = eval(config_[option_name]).name
                if image_path:
                    config_[option_name] = settings.MEDIA_URL + image_path
                else:
                    config_[option_name] = None
            except Exception as e:
                traceback.print_exc()
                config_[option_name] = None
        config_['valid'] = config_list.get(
            option_name=option_name).valid
    return config_ 
Example #14
Source File: offers.py    From volontulo with MIT License 6 votes vote down vote up
def get(request, slug, id_):
        u"""View responsible for showing details of particular offer."""
        offer = get_object_or_404(Offer, id=id_)
        try:
            main_image = OfferImage.objects.get(offer=offer, is_main=True)
        except OfferImage.DoesNotExist:
            main_image = ''

        volunteers = None
        users = [u.user.id for u in offer.organization.userprofiles.all()]
        if (
                request.user.is_authenticated() and (
                    request.user.userprofile.is_administrator or
                    request.user.userprofile.id in users
                )
        ):
            volunteers = offer.volunteers.all()

        context = {
            'offer': offer,
            'volunteers': volunteers,
            'MEDIA_URL': settings.MEDIA_URL,
            'main_image': main_image,
        }
        return render(request, "offers/show_offer.html", context=context) 
Example #15
Source File: widgets.py    From openhgsenti with Apache License 2.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 #16
Source File: tests.py    From ldap-oauth2 with GNU General Public License v3.0 5 votes vote down vote up
def test_get_logo_url(self):
        url1 = self.application1.get_logo_url()
        self.assertEqual('%sapp_logo/1235.png' % settings.MEDIA_URL, url1)

        url2 = self.application2.get_logo_url()
        self.assertEqual(None, url2) 
Example #17
Source File: static.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_media_prefix(parser, token):
    """
    Populates a template variable with the media prefix,
    ``settings.MEDIA_URL``.

    Usage::

        {% get_media_prefix [as varname] %}

    Examples::

        {% get_media_prefix %}
        {% get_media_prefix as media_prefix %}
    """
    return PrefixNode.handle_token(parser, token, "MEDIA_URL") 
Example #18
Source File: models.py    From ldap-oauth2 with GNU General Public License v3.0 5 votes vote down vote up
def get_logo_url(self):
        try:
            url = self.logo.url
            url = urljoin(settings.MEDIA_URL, url)
        except ValueError:
            url = None
        return url 
Example #19
Source File: model_media.py    From ldap-oauth2 with GNU General Public License v3.0 5 votes vote down vote up
def model_field_media_url(field):
    try:
        url = field.url
        url = urljoin(settings.MEDIA_URL, url)
    except ValueError:
        url = None
    return url 
Example #20
Source File: connector.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        settings.MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
        
        self.opts = ls.ELFINDER_CONNECTOR_OPTION_SETS['default'].copy()
        self.opts['roots'][0]['path'] = settings.MEDIA_ROOT
        self.opts['roots'][0]['URL'] = settings.MEDIA_URL
        
        self.maxDiff = None 
Example #21
Source File: widgets.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        if value is None:
            value = ''
        # 传入模板的参数
        editor_id = "id_%s" % name.replace("-", "_")
        uSettings = {
            "name": name,
            "id": editor_id,
            "value": value
        }
        if isinstance(self.command, list):
            cmdjs = ""
            if isinstance(self.command, list):
                for cmd in self.command:
                    cmdjs = cmdjs + cmd.render(editor_id)
            else:
                cmdis = self.command.render(editor_id)
            uSettings["commands"] = cmdjs

        uSettings["settings"] = self.ueditor_settings.copy()
        uSettings["settings"].update({
            "serverUrl": "/ueditor/controller/?%s" % urlencode(self._upload_settings)
        })
        # 生成事件侦听
        if self.event_handler:
            uSettings["bindEvents"] = self.event_handler.render(editor_id)

        context = {
            'UEditor': uSettings,
            'STATIC_URL': settings.STATIC_URL,
            'STATIC_ROOT': settings.STATIC_ROOT,
            'MEDIA_URL': settings.MEDIA_URL,
            'MEDIA_ROOT': settings.MEDIA_ROOT
        }
        return mark_safe(render_to_string('ueditor.html', context)) 
Example #22
Source File: app_tags.py    From developer-portal with Mozilla Public License 2.0 5 votes vote down vote up
def render_gif(block_value):
    if hasattr(block_value, "file") and hasattr(block_value.file, "name"):
        file_url = settings.MEDIA_URL + block_value.file.name
        return mark_safe(f'<img src="{file_url}" alt="">') 
Example #23
Source File: tasks.py    From Disfactory with MIT License 5 votes vote down vote up
def _upload_image_to_imgur(image_buffer, client_id):
    tmp_path = os.path.join(settings.MEDIA_ROOT, f'{uuid4()}.jpg')
    with open(tmp_path, 'wb') as fw:
        fw.write(image_buffer)
    headers = {'Authorization': f'Client-ID {client_id}'}
    data = {'image': image_buffer}
    resp = requests.post(
        'https://api.imgur.com/3/upload',
        data=data,
        headers=headers,
    )
    try:
        resp_data = resp.json()
        if 'errors' in resp_data:
            credit_resp = requests.get(
                'https://api.imgur.com/3/credits',
                headers=headers,
            )
            LOGGER.error(f'Error upload to imgur. The credits remaining: {credit_resp.json()}')
            path = urljoin(urljoin(settings.DOMAIN, settings.MEDIA_URL), os.path.basename(tmp_path))
        else:
            path = resp_data['data']['link']
    except Exception as e:
        LOGGER.error(f'Error parsing imgur response data: {resp_data}')
        path = urljoin(urljoin(settings.DOMAIN, settings.MEDIA_URL), os.path.basename(tmp_path))
    return path 
Example #24
Source File: offers.py    From volontulo with MIT License 5 votes vote down vote up
def get(request, slug, id_):  # pylint: disable=unused-argument
        """View responsible for showing join form for particular offer."""
        if request.user.is_authenticated():
            has_applied = Offer.objects.filter(
                volunteers=request.user,
                volunteers__offer=id_,
            ).count()
            if has_applied:
                messages.error(
                    request,
                    'Już wyraziłeś chęć uczestnictwa w tej ofercie.'
                )
                return redirect('offers_list')

        offer = Offer.objects.get(id=id_)
        try:
            main_image = OfferImage.objects.get(offer=offer, is_main=True)
        except OfferImage.DoesNotExist:
            main_image = ''

        context = {
            'form': OfferApplyForm(),
            'offer': offer,
            'MEDIA_URL': settings.MEDIA_URL,
            'main_image': main_image,
        }

        context['volunteer_user'] = UserProfile()
        if request.user.is_authenticated():
            context['volunteer_user'] = request.user.userprofile

        return render(
            request,
            'offers/offer_apply.html',
            context
        ) 
Example #25
Source File: offers.py    From volontulo with MIT License 5 votes vote down vote up
def get(request, slug, id_):  # pylint: disable=unused-argument
        u"""Method responsible for rendering form for offer to be changed.

        :param request: WSGIRequest instance
        :param slug: string Offer title slugified
        :param id_: int Offer database unique identifier (primary key)
        """
        offer = Offer.objects.get(id=id_)
        if offer.id or request.user.userprofile.is_administrator:
            organizations = [offer.organization]
        else:
            organizations = request.user.userprofile.organizations.all()

        return render(
            request,
            'offers/offer_form.html',
            {
                'offer': offer,
                'offer_form': CreateOfferForm(),
                'organization': offer.organization,
                'organizations': organizations,
                'offer_image_form': OfferImageForm(),
                'images': OfferImage.objects.filter(offer=offer).all(),
                'MEDIA_URL': settings.MEDIA_URL,
            }
        ) 
Example #26
Source File: desktop_app_main.py    From djanban with MIT License 5 votes vote down vote up
def run(self, netloc='0.0.0.0:9090', reload=True, log=True):
        """Run the CherryPy server."""
        from django.conf import settings
        from django.core.handlers.wsgi import WSGIHandler
        from paste.translogger import TransLogger

        url_parts = urlparse.urlsplit(netloc)
        host = "0.0.0.0"
        port = 9090
        cherrypy.config.update({
            'server.socket_host': host,
            'server.socket_port': port,
            'log.screen': False,
            'engine.autoreload.on': reload,
            'log.access_file': cherry_access_log,
            'log.error_file': cherry_error_log,
        })
        self.cfg_assets(settings.MEDIA_URL, settings.MEDIA_ROOT)
        self.cfg_assets(settings.STATIC_URL, settings.STATIC_ROOT)
        self.cfg_favicon(settings.STATIC_ROOT)
        app = WSGIHandler()
        app = TransLogger(app, logger_name='cherrypy.access',
                          setup_console_handler=False)
        if self.domains:
            app = cherrypy.wsgi.VirtualHost(app, self.domains)
        cherrypy.tree.graft(app)
        cherrypy.engine.start() 
Example #27
Source File: storage.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, location=None, base_url=None):
        if location is None:
            location = settings.MEDIA_ROOT
        self.base_location = location
        self.location = abspathu(self.base_location)
        if base_url is None:
            base_url = settings.MEDIA_URL
        self.base_url = base_url 
Example #28
Source File: context_processors.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def media(request):
    """
    Adds media-related context variables to the context.

    """
    return {'MEDIA_URL': settings.MEDIA_URL} 
Example #29
Source File: widgets.py    From luscan-devel with 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 #30
Source File: context_processors.py    From python with Apache License 2.0 5 votes vote down vote up
def media(request):
    """
    Adds media-related context variables to the context.
    """
    return {'MEDIA_URL': settings.MEDIA_URL}