7

I want to resize image(Pillow) before upload, I write code below but doesn't work! and get error:

AttributeError at /myapp/list/

_committed

Request Method: POST

Request URL: http://127.0.0.1:8000/myapp/list/ Django Version: 1.8 Exception Type: AttributeError Exception Value:

_committed

Exception Location:

/usr/local/lib/python3.4/dist-packages/Pillow-2.8.1-py3.4-linux-x86_64.egg/PIL/Image.py

In getattr, line 622 Python Executable: /usr/bin/python3.4 Python Version: 3.4.0

views.py

def list(request):
# Handle file upload
if request.method == 'POST':
    form = DocumentForm(request.POST, request.FILES)
    if form.is_valid():
        imga = request.FILES['docfile']
        size = (600, 400)
        im = Image.open(imga)
        imga = im.resize(size)
        request.FILES['docfile'] = imga
        newdoc = Document(docfile = request.FILES['docfile'], namefile=request.POST['namefile'])
        newdoc.save()

        # Redirect to the document list after POST
        return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
else:
    form = DocumentForm() # A empty, unbound form

# Load documents for the list page
documents = Document.objects.all()

# Render list page with the documents and the form
return render_to_response(
    'myapp/list.html',
    {'documents': documents, 'form': form},
    context_instance=RequestContext(request)
)
1
  • 3
    Not related to your issue, but rather the question's title: you are aware that you are resizing you image on the server side, so technically after the upload (and not before). Commented May 25, 2015 at 9:07

3 Answers 3

29
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
from resizeimage import resizeimage

class SomeModel(models.Model):
    image = models.ImageField(upload_to=your_get_file_path_callback)

    def save(self, *args, **kwargs):
        pil_image_obj = Image.open(self.image)
        new_image = resizeimage.resize_width(pil_image_obj, 100)

        new_image_io = BytesIO()
        new_image.save(new_image_io, format='JPEG')

        temp_name = self.image.name
        self.image.delete(save=False)  

        self.image.save(
            temp_name,
            content=ContentFile(new_image_io.getvalue()),
            save=False
        )

        super(SomeModel, self).save(*args, **kwargs)

P.S. for resizing I've used 'python-image-resize' https://github.com/charlesthk/python-resize-image

Sign up to request clarification or add additional context in comments.

1 Comment

What happens when you just assign self.image = new_image_io
0

For image resizing you can make use of djanof easy thumbnail library.

Below is the sample code,that i have used in my project

options = {'size': (200, 200), 'crop': True}
thumb_url =get_thumbnailer(image path).get_thumbnail(options).url

For reference https://github.com/SmileyChris/easy-thumbnails

Comments

0

There have been some helpful answers, but you might want to understand what is going on with your current code.

Your code raises that exception because of this line :

request.FILES['docfile'] = imga

What is wrong with that ? You are affecting a pillow Image object to a django ImageField element. Those are two different types and when you call you Document constructor, it might expect to find a file form field that contains a _committed attribute.

Comments

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.