How to resize before uploading pictures in Django

Comments

1 comment

  • Avatar
    Loic Verger Del Bove

    Hi Yiwei,

    Thanks for reaching out.

    If you want to add transformations during the upload, you will need to use the CloudinaryFileField class as mentioned here: https://cloudinary.com/documentation/django_image_and_video_upload#django_forms_and_models

    This is our model.py:

    from django.db import models
    from cloudinary.models import CloudinaryField
    
    class Photo(models.Model):
      image = CloudinaryField('image')

    And this is our forms.py:

    from django.forms import ModelForm      
    from cloudinary.forms import CloudinaryFileField      
    from .models import Photo
    
    class PhotoForm(ModelForm):
      class Meta:
        model = Photo
      image = CloudinaryFileField(
        attrs = { 'style': "margin-top: 30px" }, 
        options = { 
          'tags': "directly_uploaded",
          'crop': 'limit', 'width': 1000, 'height': 1000,
          'eager': [{ 'crop': 'fill', 'width': 150, 'height': 100 }]
        })

    While the eager will create a 150x100px derived image, the transformation 'crop': 'limit', 'width': 1000, 'height': 1000 will resize the image to a 1000x1000px when saving it.

    Hope it helps.

    Best,

    Loic

    0
    Comment actions Permalink

Please sign in to leave a comment.