2

I wanna save image file size in database after uploading it. How can I do that in django models? It'll also work if I can get the size in the views. But since there can be multiple images in one Community post, I am unable to get the size for each of them. My models.py file:

from django.db import models
import os


class Community(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(max_length=500)

    def __str__(self) -> str:
        return self.title


class CommunityImages(models.Model):
    post = models.ForeignKey(Community, on_delete=models.CASCADE)
    height = models.IntegerField(null=True, blank=True)
    width = models.IntegerField(null=True, blank=True)
    image = models.ImageField(upload_to='communityImages/%Y/%m/%d', blank=True, null=True, height_field='height', width_field='width')
    @property
    def images_exists(self):
        return self.communityImages.storage.exists(self.communityImages.name)
    def community(self):
        return self.post.id
    def __str__(self):
        return "%s %s " % (self.post_id, self.image, )
    class Meta:
        verbose_name_plural = "Community Images"

My views.py file:

from django.http import JsonResponse
from .models import CommunityImages, Community
import json
import os


def image_detail(request, post_id):
    community_post = {}
    communityPostImages = list(CommunityImages.objects.filter(post=post_id).values('id','image', 'height', 'width'))
    
    for i in range(len(communityPostImages)):
        communityPostImages[i]['img_name'] = os.path.split(communityPostImages[i]['image'])[-1]
        communityPostImages[i]['type'] = os.path.splitext(communityPostImages[i]['img_name'])[-1].replace('.', '')
        communityPostImages[i]['dimension'] = str(communityPostImages[i]['height']) + "x" + str(communityPostImages[i]['width'])

    community_post['communityPostImages'] = communityPostImages
    data = json.dumps(community_post, indent=4, sort_keys=False, default=str)
    return JsonResponse(data, safe=False)

Thanks in advance!

1 Answer 1

5

You can obtain this with the .size [Django-doc] attribute of the FieldFile that is stored in the FileField:

The result of the underlying Storage.size() method.

The Storage.size(…) method [Django-doc] will:

Returns the total size, in bytes, of the file referenced by name. For storage systems that aren’t able to return the file size this will raise NotImplementedError instead.

Here you thus can obtain the size of the file with:

some_community_image.image.size  # size in bytes
Sign up to request clarification or add additional context in comments.

2 Comments

I know that. But I wonder if I could do that keeping the ImageField. Thank you
@Zubayer: this also works for an ImageField, since an ImageField is a subclass of a FileField, so everything that can be done with a FileField, can be done with an ImageField.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.