Python django.conf.settings.MEDIA_URL Examples

The following are 30 code examples for showing how to use django.conf.settings.MEDIA_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: GTDWeb   Author: lanbing510   File: static.py    License: 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
Project: GTDWeb   Author: lanbing510   File: utils.py    License: 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 3
Project: GTDWeb   Author: lanbing510   File: storage.py    License: 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 4
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 5
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 6
Project: django-adminlte-ui   Author: wuyue92tree   File: adminlte_options.py    License: 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 7
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 8
Project: luscan-devel   Author: blackye   File: static.py    License: 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 9
Project: luscan-devel   Author: blackye   File: static.py    License: 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
Project: volontulo   Author: stxnext-csr   File: __init__.py    License: 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 11
Project: volontulo   Author: stxnext-csr   File: offers.py    License: 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 12
Project: openhgsenti   Author: drexly   File: utils.py    License: 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 13
Project: python2017   Author: bpgc-cte   File: utils.py    License: 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 14
Project: foundation.mozilla.org   Author: mozilla   File: homepage_tags.py    License: 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 15
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 16
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 17
Project: GTDWeb   Author: lanbing510   File: context_processors.py    License: 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 18
Project: Tenma   Author: Tenma-Server   File: simple_crop.py    License: MIT License 5 votes vote down vote up
def _create_cache_paths(filepath, width, height):
	filename = filepath.split('/')[-1]
	extension = os.path.splitext(filename)[1].lower() if os.path.splitext(filename)[1] else '.jpg'
	cache = 'CACHE/' + filename.split('.')[0] + '-' + str(width) + 'x' + str(height) + extension
	cache_static = settings.MEDIA_ROOT + '/' + cache
	cache_url = settings.MEDIA_URL + cache

	return (cache_static, cache_url) 
Example 19
Project: bioforum   Author: reBiocoder   File: static.py    License: MIT License 5 votes vote down vote up
def get_media_prefix(parser, token):
    """
    Populate 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 20
Project: bioforum   Author: reBiocoder   File: context_processors.py    License: MIT License 5 votes vote down vote up
def media(request):
    """
    Add media-related context variables to the context.
    """
    return {'MEDIA_URL': settings.MEDIA_URL} 
Example 21
Project: BikeMaps   Author: SPARLab   File: upload_image.py    License: MIT License 5 votes vote down vote up
def upload_image(request):
    form = UploadImageForm(request.POST, request.FILES)
    if form.is_valid():
        f = request.FILES['image']
        f = _handle_uploaded_file(f, form.cleaned_data['resize'])

        return JsonResponse({
            'success': True,
            'url': (settings.MEDIA_URL + "blogApp/" + f.name),
            'title': form.cleaned_data['title'],
        })

    else:
        form_html = render_crispy_form(form)
        return JsonResponse({'success': False, 'form_html': form_html}) 
Example 22
Project: jet-bridge   Author: jet-admin   File: configuration.py    License: MIT License 5 votes vote down vote up
def media_url(self, path, request):
        url = '{}{}'.format(django_settings.MEDIA_URL, path)

        if not django_settings.MEDIA_URL.startswith('http://') and not django_settings.MEDIA_URL.startswith('https://'):
            url = '{}://{}{}'.format(request.protocol, request.host, url)

        return url 
Example 23
Project: pasportaservo   Author: tejoesperanto   File: middleware.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        exclude_urls = [
            reverse('admin:index'),
            url_index_debug,
            settings.STATIC_URL,
            settings.MEDIA_URL,
            '/favicon.ico',
            url_index_maps,
        ]
        self.exclude_urls = tuple(str(url) for url in exclude_urls) 
Example 24
Project: django-tenants   Author: django-tenants   File: storage.py    License: MIT License 5 votes vote down vote up
def relative_media_url(self):
        try:
            multitenant_relative_url = settings.MULTITENANT_RELATIVE_MEDIA_ROOT
        except AttributeError:
            # MULTITENANT_RELATIVE_MEDIA_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"

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

        if not multitenant_relative_url.startswith("/"):
            multitenant_relative_url = "/" + multitenant_relative_url

        return multitenant_relative_url 
Example 25
Project: palanaeum   Author: Palanaeum   File: configuration.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _deserialize_value(key, value):
    value_type = CONFIG_ENTRIES[key][0]

    if value_type == 'str':
        return str(value)
    elif value_type == 'int':
        return int(value)
    elif value_type == 'bool':
        return value == '1'
    elif value_type == 'file':
        return urljoin(settings.MEDIA_URL, value) if value else None
    else:
        raise NotImplementedError 
Example 26
Project: gro-api   Author: OpenAgricultureFoundation   File: urls.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_current_urls():
    urls = BaseRouter.get_instance().urls + [
        url(r'^auth/', include(auth_patterns)),
        url(r'^auth/registration/', include(auth_registration_patterns)),
        url(r'^docs/', include('rest_framework_swagger.urls')),
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    if settings.DEBUG:
        import debug_toolbar
        urls.append(url(r'^__debug__/', include(debug_toolbar.urls)))
    return urls 
Example 27
Project: wagtail-cookiecutter-foundation   Author: chrisdev   File: gallery_tags.py    License: MIT License 5 votes vote down vote up
def original_url(image):
    return os.path.join(settings.MEDIA_URL, str(image.file)) 
Example 28
Project: volontulo   Author: CodeForPoznan   File: offers.py    License: 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_)

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

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

        return render(
            request,
            'offers/offer_apply.html',
            context
        ) 
Example 29
Project: InvenTree   Author: inventree   File: serializers.py    License: MIT License 5 votes vote down vote up
def to_representation(self, value):

        if not value:
            return None

        return os.path.join(str(settings.MEDIA_URL), str(value)) 
Example 30
Project: online-judge   Author: DMOJ   File: widgets.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def django_uploader(image):
    ext = os.path.splitext(image.name)[1]
    if ext not in settings.MARTOR_UPLOAD_SAFE_EXTS:
        ext = '.png'
    name = str(uuid.uuid4()) + ext
    default_storage.save(os.path.join(settings.MARTOR_UPLOAD_MEDIA_DIR, name), image)
    url_base = getattr(settings, 'MARTOR_UPLOAD_URL_PREFIX',
                       urljoin(settings.MEDIA_URL, settings.MARTOR_UPLOAD_MEDIA_DIR))
    if not url_base.endswith('/'):
        url_base += '/'
    return json.dumps({'status': 200, 'name': '', 'link': urljoin(url_base, name)})