Python django.conf.settings.STATIC_ROOT Examples

The following are 30 code examples of django.conf.settings.STATIC_ROOT(). 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: finders.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def check(self, **kwargs):
        errors = []
        if not isinstance(settings.STATICFILES_DIRS, (list, tuple)):
            errors.append(Error(
                'The STATICFILES_DIRS setting is not a tuple or list.',
                hint='Perhaps you forgot a trailing comma?',
                id='staticfiles.E001',
            ))
        for root in settings.STATICFILES_DIRS:
            if isinstance(root, (list, tuple)):
                _, root = root
            if settings.STATIC_ROOT and os.path.abspath(settings.STATIC_ROOT) == os.path.abspath(root):
                errors.append(Error(
                    'The STATICFILES_DIRS setting should not contain the '
                    'STATIC_ROOT setting.',
                    id='staticfiles.E002',
                ))
        return errors 
Example #2
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #3
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #4
Source File: finders.py    From bioforum with MIT License 6 votes vote down vote up
def check(self, **kwargs):
        errors = []
        if not isinstance(settings.STATICFILES_DIRS, (list, tuple)):
            errors.append(Error(
                'The STATICFILES_DIRS setting is not a tuple or list.',
                hint='Perhaps you forgot a trailing comma?',
                id='staticfiles.E001',
            ))
        for root in settings.STATICFILES_DIRS:
            if isinstance(root, (list, tuple)):
                _, root = root
            if settings.STATIC_ROOT and os.path.abspath(settings.STATIC_ROOT) == os.path.abspath(root):
                errors.append(Error(
                    'The STATICFILES_DIRS setting should not contain the '
                    'STATIC_ROOT setting.',
                    id='staticfiles.E002',
                ))
        return errors 
Example #5
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 #6
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #7
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #8
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #9
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #10
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #11
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 #12
Source File: finders.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, app_names=None, *args, **kwargs):
        # List of locations with static files
        self.locations = []
        # Maps dir paths to an appropriate storage instance
        self.storages = OrderedDict()
        if not isinstance(settings.STATICFILES_DIRS, (list, tuple)):
            raise ImproperlyConfigured(
                "Your STATICFILES_DIRS setting is not a tuple or list; "
                "perhaps you forgot a trailing comma?")
        for root in settings.STATICFILES_DIRS:
            if isinstance(root, (list, tuple)):
                prefix, root = root
            else:
                prefix = ''
            if settings.STATIC_ROOT and os.path.abspath(settings.STATIC_ROOT) == os.path.abspath(root):
                raise ImproperlyConfigured(
                    "The STATICFILES_DIRS setting should "
                    "not contain the STATIC_ROOT setting")
            if (prefix, root) not in self.locations:
                self.locations.append((prefix, root))
        for prefix, root in self.locations:
            filesystem_storage = FileSystemStorage(location=root)
            filesystem_storage.prefix = prefix
            self.storages[root] = filesystem_storage
        super(FileSystemFinder, self).__init__(*args, **kwargs) 
Example #13
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #14
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #15
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #16
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #17
Source File: viewsets.py    From OasisPlatform with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def resource_file(self, request, pk=None, version=None):
        """
        get:
        Gets the models `resource_file` contents

        delete:
        Disassociates the moodels `resource_file` contents
        """
        try:
            return handle_related_file(self.get_object(), 'resource_file', request, ['application/json'])
        except Http404:
            print("No resource_file set, returning default file as response")
            with io.open(os.path.join(settings.STATIC_ROOT, 'model_resource.json')) as default_resource:
                data = json.load(default_resource)
            response = JsonResponse(data)
            response['Content-Disposition'] = 'attachment; filename="{}"'.format('default_resource_file.json')
            return response 
Example #18
Source File: views.py    From Django-3-by-Example with MIT License 6 votes vote down vote up
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    html = render_to_string('orders/order/pdf.html',
                            {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = f'filename=order_{order.id}.pdf'
    weasyprint.HTML(string=html).write_pdf(response,
        stylesheets=[weasyprint.CSS(
            settings.STATIC_ROOT + 'css/pdf.css')])
    return response 
Example #19
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #20
Source File: storage.py    From django-tenants with 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 #21
Source File: pdf.py    From silver with Apache License 2.0 6 votes vote down vote up
def fetch_resources(uri, rel):
    """
    Callback to allow xhtml2pdf/reportlab to retrieve Images,Stylesheets, etc.
    `uri` is the href attribute from the html link element.
    `rel` gives a relative path, but it's not used here.
    """
    if settings.MEDIA_URL and uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif settings.STATIC_URL and uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
        if not os.path.exists(path):
            for d in settings.STATICFILES_DIRS:
                path = os.path.join(d, uri.replace(settings.STATIC_URL, ""))
                if os.path.exists(path):
                    break
    elif uri.startswith("http://") or uri.startswith("https://"):
        path = uri
    else:
        raise UnsupportedMediaPathException('media urls must start with %s or %s' % (
            settings.MEDIA_URL, settings.STATIC_URL))

    return path 
Example #22
Source File: finders.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def __init__(self, app_names=None, *args, **kwargs):
        # List of locations with static files
        self.locations = []
        # Maps dir paths to an appropriate storage instance
        self.storages = OrderedDict()
        if not isinstance(settings.STATICFILES_DIRS, (list, tuple)):
            raise ImproperlyConfigured(
                "Your STATICFILES_DIRS setting is not a tuple or list; "
                "perhaps you forgot a trailing comma?")
        for root in settings.STATICFILES_DIRS:
            if isinstance(root, (list, tuple)):
                prefix, root = root
            else:
                prefix = ''
            if settings.STATIC_ROOT and os.path.abspath(settings.STATIC_ROOT) == os.path.abspath(root):
                raise ImproperlyConfigured(
                    "The STATICFILES_DIRS setting should "
                    "not contain the STATIC_ROOT setting")
            if (prefix, root) not in self.locations:
                self.locations.append((prefix, root))
        for prefix, root in self.locations:
            filesystem_storage = FileSystemStorage(location=root)
            filesystem_storage.prefix = prefix
            self.storages[root] = filesystem_storage
        super(FileSystemFinder, self).__init__(*args, **kwargs) 
Example #23
Source File: views.py    From exist with MIT License 6 votes vote down vote up
def getSrc(self, url):
        imagehash = hashlib.md5(url.encode('utf-8')).hexdigest()
        if settings.STATIC_ROOT is None:
            filepath = settings.STATICFILES_DIRS[0] + "websrc/" + imagehash
        else:
            filepath = settings.STATIC_ROOT + "websrc/" + imagehash

        if not os.path.exists(filepath):
            ua = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko"
            headers = {
                'User-Agent': ua
            }
            try:
                res = requests.get(url, headers=headers, verify=False)
            except Exception as e:
                logger.error(e)
                return
            if "content-type" in res.headers:
                if 'text/html' in res.headers['content-type']:
                    with open(filepath, 'w') as fp:
                        fp.write(res.text)
            else:
                with open(filepath, 'wb') as fp:
                    fp.write(res.content)
        return imagehash 
Example #24
Source File: views.py    From exist with MIT License 6 votes vote down vote up
def getImage(self, url):
        imagehash = hashlib.md5(url.encode('utf-8')).hexdigest()
        if settings.STATIC_ROOT is None:
            filepath = settings.STATICFILES_DIRS[0] + "webimg/" + imagehash + ".png"
        else:
            filepath = settings.STATIC_ROOT + "webimg/" + imagehash + ".png"
        path = "static/webimg/" + imagehash + ".png"
        options = {
            'quiet': '',
            'xvfb': '',
        }
        if not os.path.exists(filepath):
            try:
                imgkit.from_url(url, filepath, options=options)
            except Exception as e:
                logger.error(e)
                return
        return path 
Example #25
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 #26
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 #27
Source File: finders.py    From python2017 with MIT License 6 votes vote down vote up
def __init__(self, app_names=None, *args, **kwargs):
        # List of locations with static files
        self.locations = []
        # Maps dir paths to an appropriate storage instance
        self.storages = OrderedDict()
        if not isinstance(settings.STATICFILES_DIRS, (list, tuple)):
            raise ImproperlyConfigured(
                "Your STATICFILES_DIRS setting is not a tuple or list; "
                "perhaps you forgot a trailing comma?")
        for root in settings.STATICFILES_DIRS:
            if isinstance(root, (list, tuple)):
                prefix, root = root
            else:
                prefix = ''
            if settings.STATIC_ROOT and os.path.abspath(settings.STATIC_ROOT) == os.path.abspath(root):
                raise ImproperlyConfigured(
                    "The STATICFILES_DIRS setting should "
                    "not contain the STATIC_ROOT setting")
            if (prefix, root) not in self.locations:
                self.locations.append((prefix, root))
        for prefix, root in self.locations:
            filesystem_storage = FileSystemStorage(location=root)
            filesystem_storage.prefix = prefix
            self.storages[root] = filesystem_storage
        super(FileSystemFinder, self).__init__(*args, **kwargs) 
Example #28
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 #29
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def link_callback(uri, rel):
    # convert URIs to absolute system paths
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        # handle absolute uri (i.e., "http://my.tld/a.png")
        return uri

    # make sure that the local file exists
    if not os.path.isfile(path):
        raise Exception(
            "Media URI must start with "
            f"'{settings.MEDIA_URL}' or '{settings.STATIC_URL}'")

    return path 
Example #30
Source File: views.py    From Django-2-by-Example with MIT License 5 votes vote down vote up
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    html = render_to_string('orders/order/pdf.html',
                            {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename=order_{}.pdf"'.format(order.id)
    weasyprint.HTML(string=html).write_pdf(response,
        stylesheets=[weasyprint.CSS(
            settings.STATIC_ROOT + 'css/pdf.css')])
    return response