Python django.template.defaultfilters 模块,filesizeformat() 实例源码

我们从Python开源项目中,提取了以下29个代码示例,用于说明如何使用django.template.defaultfilters.filesizeformat()

项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def check(request):
    return {
            'hostname': socket.gethostname(),
            'ips': ips,
            'cpus': psutil.cpu_count(),
            'uptime': timesince(datetime.fromtimestamp(psutil.boot_time())),
            'memory': {
                'total': filesizeformat(psutil.virtual_memory().total),
                'available': filesizeformat(psutil.virtual_memory().available),
                'used': filesizeformat(psutil.virtual_memory().used),
                'free': filesizeformat(psutil.virtual_memory().free),
                'percent': psutil.virtual_memory().percent
            },
            'swap': {
                'total': filesizeformat(psutil.swap_memory().total),
                'used': filesizeformat(psutil.swap_memory().used),
                'free': filesizeformat(psutil.swap_memory().free),
                'percent': psutil.swap_memory().percent
            }
        }
项目:wagtailvideos    作者:takeflight    | 项目源码 | 文件源码
def test_add_too_large_file(self):
        video_file = create_test_video_file()

        response = self.post({
            'title': "Test video",
            'file': SimpleUploadedFile('small.mp4', video_file.read(), "video/mp4"),
        })

        # Shouldn't redirect anywhere
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtailvideos/videos/add.html')

        # The form should have an error
        self.assertFormError(
            response, 'form', 'file',
            "This file is too big ({file_size}). Maximum filesize {max_file_size}.".format(
                file_size=filesizeformat(video_file.size),
                max_file_size=filesizeformat(1),
            )
        )
项目:django-private-storage    作者:edoburu    | 项目源码 | 文件源码
def clean(self, *args, **kwargs):
        data = super(PrivateFileField, self).clean(*args, **kwargs)
        file = data.file
        if isinstance(file, UploadedFile):
            # content_type is only available for uploaded files,
            # and not for files which are already stored in the model.
            content_type = file.content_type

            if self.content_types and content_type not in self.content_types:
                logger.debug('Rejected uploaded file type: %s', content_type)
                raise ValidationError(self.error_messages['invalid_file_type'])

            if self.max_file_size and file.size > self.max_file_size:
                raise ValidationError(self.error_messages['file_too_large'].format(
                    max_size=filesizeformat(self.max_file_size),
                    size=filesizeformat(file.size)
                ))

        return data
项目:wypok    作者:arturtamborski    | 项目源码 | 文件源码
def __call__(self, data):
        if self.max_size is not None and data.size > self.max_size:
            params = {
                'max_size': filesizeformat(self.max_size),
                'size': filesizeformat(data.size),
            }
            raise ValidationError(self.error_messages['max_size'], 'max_size', params)

        if self.min_size is not None and data.size < self.min_size:
            params = {
                'min_size': filesizeformat(self.mix_size),
                'size': filesizeformat(data.size)
            }
            raise ValidationError(self.error_messages['min_size'], 'min_size', params)

        if self.content_types is not None and len(self.content_types):
            content_type = magic.from_buffer(data.read(), mime=True)
            data.seek(0) # seek to start for future mime checks by django

            if content_type not in self.content_types:
                params = {
                    'content_type': content_type
                }
                raise ValidationError(self.error_messages['content_type'], 'content_type', params)
项目:Wagtail-Image-Folders    作者:anteatersa    | 项目源码 | 文件源码
def test_add_too_large_file(self):
        file_content = get_test_image_file().file.getvalue()

        response = self.post({
            'title': "Test image",
            'file': SimpleUploadedFile('test.png', file_content),
        })

        # Shouldn't redirect anywhere
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtailimages/images/add.html')

        # The form should have an error
        self.assertFormError(
            response, 'form', 'file',
            "This file is too big ({file_size}). Maximum filesize {max_file_size}.".format(
                file_size=filesizeformat(len(file_content)),
                max_file_size=filesizeformat(1),
            )
        )
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def get_size_used(container):
    return filters.filesizeformat(container.bytes)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def get_size(obj):
    if obj.bytes is None:
        return _("pseudo-folder")
    return filters.filesizeformat(obj.bytes)
项目:BioQueue    作者:liyao001    | 项目源码 | 文件源码
def clean(self, data, initial=None):
        file = super(RestrictedFileField, self).clean(data, initial)

        try:
            content_type = file.content_type
            if content_type in self.content_types:
                if file._size > self.max_upload_size:
                    raise ValidationError(_('Please keep filesize under %s. Current filesize %s') % (
                        filesizeformat(self.max_upload_size), filesizeformat(file._size)))
            else:
                raise ValidationError(_('Filetype not supported.'))
        except AttributeError:
            pass

        return data
项目:tecken    作者:mozilla-services    | 项目源码 | 文件源码
def filesizeformat(bytes):
    """the function django.template.defaultfilters.filesizeformat is
    nifty but it's meant for displaying in templates so it uses a
    whitespace-looking character instead of a space so it doesn't
    break in display. We don't need that here in this context."""
    return dj_filesizeformat(bytes).replace('\xa0', ' ')
项目:registration    作者:HackAssistant    | 项目源码 | 文件源码
def clean_receipt(self):
        receipt = self.cleaned_data['receipt']
        size = getattr(receipt, '_size', 0)
        if size > settings.MAX_UPLOAD_SIZE:
            raise forms.ValidationError("Please keep resume under %s. Current filesize %s" % (
                filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(size)))
        return receipt
项目:registration    作者:HackAssistant    | 项目源码 | 文件源码
def clean_resume(self):
        resume = self.cleaned_data['resume']
        size = getattr(resume, '_size', 0)
        if size > settings.MAX_UPLOAD_SIZE:
            raise forms.ValidationError("Please keep resume size under %s. Current filesize %s" % (
                filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(size)))
        return resume
项目:steemprojects.com    作者:noisy    | 项目源码 | 文件源码
def clean(self, *args, **kwargs):
        data = super(SizeAndContentTypeRestrictedImageField, self).clean(*args, **kwargs)

        file = data.file
        try:
            content_type = file.content_type
            if content_type in self.content_types:
                if file._size > self.max_upload_size:
                    raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
            else:
                raise forms.ValidationError(_('Filetype not supported.'))
        except AttributeError:
            pass

        return data
项目:2017.1-PlataformaJogosUnB    作者:fga-gpp-mds    | 项目源码 | 文件源码
def validate_package_size(package):
    KILOBYTE = 1024
    MAX_UPLOAD_SIZE = 5 * KILOBYTE ** 3
    if(_get_size(package) > MAX_UPLOAD_SIZE):
        raise ValidationError(
            _('Please keep filesize under %s. Current filesize %s')
            % (filesizeformat(MAX_UPLOAD_SIZE), filesizeformat(package.size))
        )
项目:2017.1-PlataformaJogosUnB    作者:fga-gpp-mds    | 项目源码 | 文件源码
def size(self):
        return filesizeformat(self.package.size)
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def filtered_filesizeformat(value):
    """
    If the value is -1 return an empty string. Otherwise,
    change output from fileformatsize to suppress trailing '.0'
    and change 'bytes' to 'B'.
    """
    if value == -1:
        return ''

    return filesizeformat(value).replace("bytes", "B")
项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def validate_size(value, max_size=20*1024*1024, error_messages=None):
    """ ????????? ???? ???????? """
    error_messages = error_messages or {}

    if max_size and value.size > max_size:
        raise ValidationError(
            error_messages.get(
                'too_big',
                _('Image must be no larger than %(limit)s')
            ) % {
                'current': filesizeformat(value.size),
                'limit': filesizeformat(max_size),
            },
            code='too_big',
        )
项目:django-db-storage    作者:derekkwok    | 项目源码 | 文件源码
def file_size(self, obj):
        return filesizeformat(obj.size)
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def __init__(self, request, node, ns, *args, **kwargs):
        super(NodeStorageForm, self).__init__(request, ns, *args, **kwargs)
        self.fields['owner'].choices = get_owners(request).values_list('username', 'username')
        node_zpools = node.zpools
        zpools = [(k, '%s (%s)' % (k, filesizeformat(int(v['size']) * 1048576))) for k, v in node_zpools.items()]

        # Add zpools for NodeStorage objects that have vanished from compute node (Issue #chili-27)
        for zpool in node.nodestorage_set.exclude(zpool__in=node_zpools.keys()).values_list('zpool', flat=True):
            zpools.append((zpool, '%s (???)' % zpool))

        self.fields['zpool'].choices = zpools
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def disk_id_option(array_disk_id, disk):
    """Text for option in Disk ID select field"""
    return _('Disk') + ' %d (%s)' % (array_disk_id, filesizeformat(int(disk['size']) * 1048576))
项目:wagtailvideos    作者:takeflight    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(WagtailVideoField, self).__init__(*args, **kwargs)

        # Get max upload size from settings
        self.max_upload_size = getattr(settings, 'WAGTAILVIDEOS_MAX_UPLOAD_SIZE', 1024 * 1024 * 1024)
        max_upload_size_text = filesizeformat(self.max_upload_size)

        # Help text
        if self.max_upload_size is not None:
            self.help_text = _(
                "Maximum filesize: %(max_upload_size)s."
            ) % {
                'max_upload_size': max_upload_size_text,
            }

        # Error messages
        self.error_messages['invalid_video_format'] = _(
            "Not a valid video. Content type was %s."
        )

        self.error_messages['file_too_large'] = _(
            "This file is too big (%%s). Maximum filesize %s."
        ) % max_upload_size_text

        self.error_messages['file_too_large_unknown_size'] = _(
            "This file is too big. Maximum filesize %s."
        ) % max_upload_size_text
项目:wagtailvideos    作者:takeflight    | 项目源码 | 文件源码
def check_video_file_size(self, f):
        # Upload size checking can be disabled by setting max upload size to None
        if self.max_upload_size is None:
            return

        # Check the filesize
        if f.size > self.max_upload_size:
            raise ValidationError(self.error_messages['file_too_large'] % (
                filesizeformat(f.size),
            ), code='file_too_large')
项目:wagtaildraftail    作者:springload    | 项目源码 | 文件源码
def get_document_meta(document):
    """
    :type document: wagtail.wagtaildocs.models.Document (or subclass)
    :param document: the document
    :rtype: dict
    :return: the document size and extension
    """

    return {
        'extension': document.file_extension.lower(),
        'size': filesizeformat(document.file.size)
    }
项目:django-icekit    作者:ic-labs    | 项目源码 | 文件源码
def file_size(self):
        """
        Obtain the file size for the file in human readable format.
        If the file isn't fount, return "0 bytes" rather than crash

        :return: String of file size with unit.

        """
        try:
            return filesizeformat(self.file.size)
        except OSError:
            return filesizeformat(0)
项目:django-icekit    作者:ic-labs    | 项目源码 | 文件源码
def file_size(self):
        """
        Obtain the file size for the file in human readable format.

        :return: String of file size with unit.
        """
        try:
            return filesizeformat(self.image.size)
        except (OSError, IOError):
            return filesizeformat(0)
项目:CSE371Project    作者:muhakh    | 项目源码 | 文件源码
def clean(self, *args, **kwargs):
        data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)

        file = data.file
        try:
            content_type = file.content_type
            if content_type in self.content_types:
                if file._size > self.max_upload_size:
                    raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
            else:
                raise forms.ValidationError(_('Filetype not supported.'))
        except AttributeError:
            pass

        return data
项目:harnas    作者:harnasproject    | 项目源码 | 文件源码
def clean(self):
        solution = self.cleaned_data['solution']
        max_solution_size = self.cleaned_data['task'].max_solution_size
        if solution._size > max_solution_size:
            error_message = 'You cannot upload files larger than %(max_size)s.'
            max_size = filesizeformat(max_solution_size)
            raise forms.ValidationError(_(error_message),
                                        params={'max_size': max_size},
                                        code='too_large_solution')
项目:Wagtail-Image-Folders    作者:anteatersa    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(WagtailImageField, self).__init__(*args, **kwargs)

        # Get max upload size from settings
        self.max_upload_size = getattr(settings, 'WAGTAILIMAGES_MAX_UPLOAD_SIZE', 10 * 1024 * 1024)
        max_upload_size_text = filesizeformat(self.max_upload_size)

        # Help text
        if self.max_upload_size is not None:
            self.help_text = _(
                "Supported formats: %(supported_formats)s. Maximum filesize: %(max_upload_size)s."
            ) % {
                'supported_formats': SUPPORTED_FORMATS_TEXT,
                'max_upload_size': max_upload_size_text,
            }
        else:
            self.help_text = _(
                "Supported formats: %(supported_formats)s."
            ) % {
                'supported_formats': SUPPORTED_FORMATS_TEXT,
            }

        # Error messages
        self.error_messages['invalid_image'] = _(
            "Not a supported image format. Supported formats: %s."
        ) % SUPPORTED_FORMATS_TEXT

        self.error_messages['invalid_image_known_format'] = _(
            "Not a valid %s image."
        )

        self.error_messages['file_too_large'] = _(
            "This file is too big (%%s). Maximum filesize %s."
        ) % max_upload_size_text

        self.error_messages['file_too_large_unknown_size'] = _(
            "This file is too big. Maximum filesize %s."
        ) % max_upload_size_text
项目:Wagtail-Image-Folders    作者:anteatersa    | 项目源码 | 文件源码
def check_image_file_size(self, f):
        # Upload size checking can be disabled by setting max upload size to None
        if self.max_upload_size is None:
            return

        # Check the filesize
        if f.size > self.max_upload_size:
            raise ValidationError(self.error_messages['file_too_large'] % (
                filesizeformat(f.size),
            ), code='file_too_large')
项目:internet-of-things    作者:softbutterfly    | 项目源码 | 文件源码
def __call__(self, value):
        """
        Check the extension, content type and file size.
        """

        # Check the extension
        ext = splitext(value.name)[1][1:].lower()
        if self.allowed_extensions and ext not in self.allowed_extensions:
            message = self.extension_message % {
                'extension': ext,
                'allowed_extensions': ', '.join(self.allowed_extensions)
            }

            raise ValidationError(message)

        # Check the content type
        mimetype = mimetypes.guess_type(value.name)[0]
        if self.allowed_mimetypes and mimetype not in self.allowed_mimetypes:
            message = self.mime_message % {
                'mimetype': mimetype,
                'allowed_mimetypes': ', '.join(self.allowed_mimetypes)
            }

            raise ValidationError(message)

        # Check the file size
        filesize = len(value)
        if self.max_size and filesize > self.max_size:
            message = self.max_size_message % {
                'size': filesizeformat(filesize),
                'allowed_size': filesizeformat(self.max_size)
            }

            raise ValidationError(message)

        elif filesize < self.min_size:
            message = self.min_size_message % {
                'size': filesizeformat(filesize),
                'allowed_size': filesizeformat(self.min_size)
            }

            raise ValidationError(message)