简体   繁体   中英

Django — crop and save Imagefield in model.Imagefield

I need to cut the rescued image from the form and store it in the model.ImageField

My models.py

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 an instance of the model

Try this:

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

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

Then just set the image name for the image field and save the object. This time the path should be relative, since it will be used for the image url (I'm assuming you are already serving your media files):

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

PS: Don't name object variables with a leading uppercase, it's a bad practice (use user instead of User). Only class names should start with uppercase. Also, the Python convention is to use underscores as word separators in variable names (use new_image instead of newImage, write_form instead of writeFrom), instead camel case, except in class names, where is ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM