Django - Imagefield crop and preservation in model.Imagefield

I need to cut the saved image from the form and save it in model.ImageField

My .py models

class Story(models.Model): 
  creator = models.ForeignKey(User_info)
  storyid = models.AutoField(primary_key=True)
  text = models.TextField()
  title = models.CharField(max_length=255)
  photo = models.ImageField(upload_to='story_picture')

My views.py

from PIL import Image
from io import BytesIO
from django.core.files import File

def post(self, request, *args, **kwargs):                       

    form = writeForm(request.POST, request.FILES)
    print form

    User = request.user
    usuario = User_info.objects.get(user=User.id)

    story = Story()
    story.creator = usuario
    story.text = request.POST['story']
    story.title = request.POST['title']

    newImage =  Image.open(form.cleaned_data['photo'])

    story.photo = newImage.crop((10,10,800,800))    

    story.save()

I need to crop the image before asosiarla to the model instance

+4
source share
1 answer

Try the following:

Save the cropped area somewhere in the root directory of your media (make sure the path is absolute):

story.save(settings.MEDIA_ROOT + 'something.jpeg')

Then simply set the image name for the image field and save the object. This time, the path should be relative, as it will be used for the image URL (I assume that you are already serving your media files):

obj.image_field.name = '/media/something.jpeg'
obj.save()

P.S.: , ( ). . , Python ( new_image newImage, write_form writeFrom), , , .

+1

All Articles