How to properly store image dimensions in Django
I have the following model:
from django_resized import ResizedImageField
class PostImage(models.Model):
image = ResizedImageField(
size=[1200, 1200],
quality=85,
upload_to="post_images/",
blank=True,
null=True,
force_format="WEBP",
keep_meta=False,
width_field="width",
height_field="height",
)
width = models.IntegerField(null=True, blank=True)
height = models.IntegerField(null=True, blank=True)
Now the problem I am facing is:
- If the image file does not exist, it throws an exception. I was expecting for it to just send the image path, if it does not exist, the frontend will show the
altvalue or whatever. The reason it throws an error, according to chatgpt, is because it's evaluating the width and height during request time, so it needs to access the file on every request I guess?
Claude is suggesting to remove the width_field and height_field altogether, and in the create() method of the serializer, do the following:
from PIL import Image as PilImage
for image_data in uploaded_images:
img = PilImage.open(image_data)
width, height = img.size
image_data.seek(0)
PostImage.objects.create(post=post, image=image_data, width=width, height=height)
Is this okay? I couldn't find a solution online that is used by actual industries.
Django’s ImageField has two built-in parameters specifically designed for this. When you upload an image, Django automatically extracts the dimensions and populates the designated fields.
The Implementation of possible solution
from django.db import models
class MyModel(models.Model):
image = models.ImageField(
upload_path='uploads/',
width_field='image_width', # Reference to the field name
height_field='image_height' # Reference to the field name
)
# These fields must exist; Django fills them automatically
image_width = models.PositiveIntegerField(null=True, blank=True, editable=False)
image_height = models.PositiveIntegerField(null=True, blank=True, editable=False)