Python django.template.defaultfilters.filesizeformat() Examples

The following are 30 code examples of django.template.defaultfilters.filesizeformat(). 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.template.defaultfilters , or try the search function .
Example #1
Source File: fields.py    From django-private-storage with Apache License 2.0 8 votes vote down vote up
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 
Example #2
Source File: test_admin_views.py    From wagtail with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
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),
            )
        ) 
Example #3
Source File: test_admin_views.py    From wagtailvideos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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),
            )
        ) 
Example #4
Source File: test_filesizeformat.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_localized_formats(self):
        with self.settings(USE_L10N=True), translation.override('de'):
            self.assertEqual(filesizeformat(1023), '1023\xa0Bytes')
            self.assertEqual(filesizeformat(1024), '1,0\xa0KB')
            self.assertEqual(filesizeformat(10 * 1024), '10,0\xa0KB')
            self.assertEqual(filesizeformat(1024 * 1024 - 1), '1024,0\xa0KB')
            self.assertEqual(filesizeformat(1024 * 1024), '1,0\xa0MB')
            self.assertEqual(filesizeformat(1024 * 1024 * 50), '50,0\xa0MB')
            self.assertEqual(filesizeformat(1024 * 1024 * 1024 - 1), '1024,0\xa0MB')
            self.assertEqual(filesizeformat(1024 * 1024 * 1024), '1,0\xa0GB')
            self.assertEqual(filesizeformat(1024 * 1024 * 1024 * 1024), '1,0\xa0TB')
            self.assertEqual(filesizeformat(1024 * 1024 * 1024 * 1024 * 1024), '1,0\xa0PB')
            self.assertEqual(filesizeformat(1024 * 1024 * 1024 * 1024 * 1024 * 2000), '2000,0\xa0PB')
            self.assertEqual(filesizeformat(complex(1, -1)), '0\xa0Bytes')
            self.assertEqual(filesizeformat(""), '0\xa0Bytes')
            self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"), '0\xa0Bytes') 
Example #5
Source File: host.py    From django-heartbeat with MIT License 6 votes vote down vote up
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
            }
        } 
Example #6
Source File: __init__.py    From astrobin with GNU Affero General Public License v3.0 6 votes vote down vote up
def upload_size_error(request, max_size, image=None):
    subscriptions_url = reverse('subscription_list')
    open_link = "<a href=\"%s\">" % subscriptions_url
    close_link = "</a>"
    msg = "Sorry, but this image is too large. Under your current subscription plan, the maximum allowed image size is %(max_size)s. %(open_link)sWould you like to upgrade?%(close_link)s"

    messages.error(request, _(msg) % {
        "max_size": filesizeformat(max_size),
        "open_link": open_link,
        "close_link": close_link
    })

    if image is not None:
        return HttpResponseRedirect(image.get_absolute_url())

    return HttpResponseRedirect('/upload/') 
Example #7
Source File: fields.py    From djangocms-forms with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def clean(self, *args, **kwargs):
        uploaded_file = super(FormBuilderFileField, self).clean(*args, **kwargs)
        if not uploaded_file:
            if self.required:
                raise forms.ValidationError(_('This field is required.'))
            return uploaded_file

        if not os.path.splitext(uploaded_file.name)[1].lstrip('.').lower() in \
                self.allowed_file_types:
            raise forms.ValidationError(
                _('Sorry, this filetype is not allowed. '
                  'Allowed filetype: %s') % ', '.join(self.allowed_file_types))

        if uploaded_file._size > self.max_upload_size:
            params = {
                'max_size': filesizeformat(self.max_upload_size),
                'size': filesizeformat(uploaded_file._size)
            }
            msg = _(
                'Please keep file size under %(max_size)s. Current size is %(size)s.') % params
            raise forms.ValidationError(msg)

        return uploaded_file 
Example #8
Source File: tables.py    From avos with Apache License 2.0 5 votes vote down vote up
def get_size(obj):
    if obj.bytes is None:
        return _("pseudo-folder")
    return filters.filesizeformat(obj.bytes) 
Example #9
Source File: tables.py    From avos with Apache License 2.0 5 votes vote down vote up
def get_size_used(container):
    return filters.filesizeformat(container.bytes) 
Example #10
Source File: test_filesizeformat.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_formats(self):
        self.assertEqual(filesizeformat(1023), '1023\xa0bytes')
        self.assertEqual(filesizeformat(1024), '1.0\xa0KB')
        self.assertEqual(filesizeformat(10 * 1024), '10.0\xa0KB')
        self.assertEqual(filesizeformat(1024 * 1024 - 1), '1024.0\xa0KB')
        self.assertEqual(filesizeformat(1024 * 1024), '1.0\xa0MB')
        self.assertEqual(filesizeformat(1024 * 1024 * 50), '50.0\xa0MB')
        self.assertEqual(filesizeformat(1024 * 1024 * 1024 - 1), '1024.0\xa0MB')
        self.assertEqual(filesizeformat(1024 * 1024 * 1024), '1.0\xa0GB')
        self.assertEqual(filesizeformat(1024 * 1024 * 1024 * 1024), '1.0\xa0TB')
        self.assertEqual(filesizeformat(1024 * 1024 * 1024 * 1024 * 1024), '1.0\xa0PB')
        self.assertEqual(filesizeformat(1024 * 1024 * 1024 * 1024 * 1024 * 2000), '2000.0\xa0PB')
        self.assertEqual(filesizeformat(complex(1, -1)), '0\xa0bytes')
        self.assertEqual(filesizeformat(""), '0\xa0bytes')
        self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"), '0\xa0bytes') 
Example #11
Source File: fields.py    From wagtailvideos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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') 
Example #12
Source File: models.py    From feedsubs with MIT License 5 votes vote down vote up
def __str__(self):
        rv = 'Attachment {} {}'.format(self.pk, self.title)
        if self.size_in_bytes:
            rv += ' - {}'.format(filesizeformat(self.size_in_bytes))
        if self.duration:
            rv += ' - {}'.format(self.duration)
        return rv 
Example #13
Source File: fields.py    From wagtailvideos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #14
Source File: forms.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
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 
Example #15
Source File: forms.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
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)) 
Example #16
Source File: test_filesizeformat.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_negative_numbers(self):
        self.assertEqual(filesizeformat(-100), '-100\xa0bytes')
        self.assertEqual(filesizeformat(-1024 * 1024 * 50), '-50.0\xa0MB') 
Example #17
Source File: fields.py    From steemprojects.com with MIT License 5 votes vote down vote up
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 
Example #18
Source File: repairs.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_attachment(self):
        max_filesize = 10 * 1024 * 1024  # 10MB
        from django.template.defaultfilters import filesizeformat
        f = self.cleaned_data.get('attachment')
        if f and f.size > max_filesize:
            size = filesizeformat(max_filesize)
            error = _('Attachment should be no larger than %s') % size
            raise forms.ValidationError(error)

        return f 
Example #19
Source File: forms.py    From registration with MIT License 5 votes vote down vote up
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 
Example #20
Source File: forms.py    From registration with MIT License 5 votes vote down vote up
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 
Example #21
Source File: forms.py    From ldap-oauth2 with GNU General Public License v3.0 5 votes vote down vote up
def clean_profile_picture(self):
        profile_picture = self.cleaned_data['profile_picture']
        content_type = profile_picture.content_type.split('/')[0]
        if content_type in ['image']:
            if profile_picture.size > 5242880:
                raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (
                    filesizeformat(5242880), filesizeformat(profile_picture.size)))
        else:
            raise forms.ValidationError(_('File type is not supported'))
        return profile_picture 
Example #22
Source File: tables.py    From scirius with GNU General Public License v3.0 5 votes vote down vote up
def render_size(self, value):
        return filesizeformat(value) 
Example #23
Source File: fields.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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') 
Example #24
Source File: files.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def file_size(file, article):
    try:
        return filesizeformat(file.get_file_size(article))
    except BaseException:
        return 0 
Example #25
Source File: validators.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_size(content):
    """Validates if the size of the content in not too big."""
    if content.file.size > validate_size.MAX_UPLOAD_SIZE:
        message = format_lazy(
            _("Please keep filesize under {limit}. Current filesize {current}"),
            limit=filesizeformat(validate_size.MAX_UPLOAD_SIZE),
            current=filesizeformat(content.file.size))
        raise ValidationError(message, code='file-size') 
Example #26
Source File: forms.py    From dissemin with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean_upl(self):
        content = self.cleaned_data['upl']
        logger.info(content.content_type)
        if content.size > DEPOSIT_MAX_FILE_SIZE:
            raise forms.ValidationError(_('File too large (%(size)s). Maximum size is %(maxsize)s.') %
                                        {'size': filesizeformat(content._size),
                                         'maxsize': filesizeformat(DEPOSIT_MAX_FILE_SIZE)},
                                        code='too_large')
        return content 
Example #27
Source File: forms.py    From BioQueue with Apache License 2.0 5 votes vote down vote up
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 
Example #28
Source File: catalog.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def filesize(self):
        try:
            return filesizeformat(int(self.size))
        except ValueError:
            return self.size 
Example #29
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_photo(self):
        MAX_FILESIZE = 1*1024*1024 # 1 MB
        from django.template.defaultfilters import filesizeformat
        photo = self.cleaned_data.get('photo')
        if photo and photo.size > MAX_FILESIZE:
            size = filesizeformat(MAX_FILESIZE)
            error = _('Profile picture should be no larger than %s') % size
            raise forms.ValidationError(error)

        return photo 
Example #30
Source File: fields.py    From wagtail with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Get max upload size from settings
        self.max_upload_size = getattr(settings, 'WAGTAILIMAGES_MAX_UPLOAD_SIZE', 10 * 1024 * 1024)
        self.max_image_pixels = getattr(settings, 'WAGTAILIMAGES_MAX_IMAGE_PIXELS', 128 * 1000000)
        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_extension'] = _(
            "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_many_pixels'] = _(
            "This file has too many pixels (%%s). Maximum pixels %s."
        ) % self.max_image_pixels

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